[英]How to write specific lines of a text to a new file?
I have a text file from which I want to find specific lines and write them to a new file. 我有一个文本文件,我想从中查找特定行并将其写入新文件。 the text looks something like this:
文字看起来像这样:
1552311_a_at NA 6.548202118 6.795958567 6.525295817 6.467153775
1552312_a_at NA 7.237622005 7.501887409 7.438287339 7.249551462
1552334_at NA 5.36199913 5.554097857 5.296649894 5.64695338
I've done this before without many problems, but for some reason it won't work for me in this instance. 我之前没有做过很多问题,但是出于某种原因,在这种情况下它对我不起作用。 I have a list of values I'm looking for in the text file to extract.
我在文本文件中要提取的值列表。
import fileinput
x = open('file', 'r')
y = open('file_write', 'w')
z = [...,...,...] #list of values to search for in file given by user
def file_transform(filein,fileout,list):
for i in list:
for line in filein:
if list[i] in line:
fileout.write(line)
file_transform(x,y,z)
file.close()
file_write.close()
the script runs, but I end up with an empty new text file. 该脚本运行,但是最终我得到一个空的新文本文件。 I cannot understand where I'm going wrong.
我不明白我要去哪里错了。
You cannot cycle multiple times the same file without "rewinding", also you are misusing for cycle on list: 您可以在同一文件中未循环多次使用,而不“倒带”,还你滥用对列表循环:
def file_transform(filein,fileout,z):
for i in z:
for line in filein:
if i in line:
fileout.write(line)
filein.seek(0)
or, much better: 或者更好:
def file_transform(filein,fileout,z):
for line in filein:
for i in z:
if i in line:
fileout.write(line)
When you do for i in z
i actually contains elements of list not indexes. 当您
for i in z
i进行操作时for i in z
实际上包含列表元素而不是索引。 For more information see this . 欲了解更多信息,请参阅本 。
list
is not a good name for any variable, as list
is an object-type in python. list
不是任何变量的好名字,因为list
是python中的对象类型。
with open('file', 'r') as f:
x = f.readlines() # this auto closes the file after reading, which is better practice
y = open('file_write', 'w')
def file_transform(filein, fileout, z):
for line in filein:
for i in z:
if i in line:
fileout.write(line)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.