更快地读取和写入文本文件

时间:2019-02-13 04:38:32

标签: python

我有以下代码,我在其中读取输入列表,将其反斜杠分割,然后将变量evid附加到evids数组中。接下来,我打开一个名为evids.txt的文件,并将evids写入该文件。如何加快/减少此代码中的行数?谢谢。

evids = []
with open('evid_list.txt', 'r') as infile:
    data = infile.readlines()
    for i in data:
        evid = i.split('/')[2]
        evids.append(evid)

with open('evids.txt', 'w') as f:
    for i in evids:
        f.write("%s" % i)

1 个答案:

答案 0 :(得分:3)

with open('evid_list.txt', 'r') as infile, open('evids.txt', 'w') as ofile:
    for line in infile:
        ofile.write('{}\n'.format(line.split('/')[2]))