我有一些文字:
228;u;Ali;
129;cr;Daan;
730;c;Arton;
466;cr;Frynk;
314;c;Katuhkay;
9822;c;Kinberley;
我想将此文本写入文件,但我只想写出带符号的行'; cr;'
答案 0 :(得分:0)
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))
如果您希望从网络上读取数据,请使用以下命令:
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(...) read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
为了写入文件,'\n'.join([elem1,...])
从包含'; cr;'的所有inpList元素创建一个字符串。此字符串传递给write(str)
,它将字符串输出到输出文件。