私はいくつかのテキストを持っています:
228;u;Ali;
129;cr;Daan;
730;c;Arton;
466;cr;Frynk;
314;c;Katuhkay;
9822;c;Kinberley;
このテキストをファイルに書き込みたいのですが、記号';cr;'のある行だけを書きたいです。
このようなもの:
with open("input.txt") as f,open("output.txt","w") as f2:
for line in f: #iterate over each line of input.txt
if ";cr;" in line: #if ';cr;' is found
f2.write(line+'\n') #then write that line to "output.txt"
Python では、以下を使用して部分文字列を簡単に確認できますin
。
In [167]: "f" in "qwertyferty"
Out[167]: True
In [168]: "z" in "qwertyferty"
Out[168]: False
with open("input.csv", "r") as inp, open("output","w") as out:
inpList = inp.read().split()
out.write('\n'.join(el for el in inpList if ';cr;' in el))
Web からデータを読み取りたい場合は、次を使用します。
from urllib2 import urlopen
inp = urlopen("<URL>")
with open("output","w") as out:
inpList = inp.read().split()
out.write('\n'.join(el for el in inpList if ';cr;' in el))
read()
ファイル全体を一度に読み取ります。split()
空白で区切られたリストに分割します。
読んだ(...) read([size]) -> 最大 size バイトを読み取り、文字列として返します。 size 引数が負の値または省略されている場合、EOF に達するまで読み取ります。
ファイルに書き込むために、'\n'.join([elem1,...])
「;cr;」を含むすべての inpList 要素から文字列を作成します。write(str)
この文字列は、文字列を出力ファイルに出力する に渡されます。