![](/img/trans.png)
[英]Python: How to check a text file, compare it to each line in another text file, and print the lines that do not match
[英]How to check each line of a text file for a string and print all lines with occurrences of that word to a new text file?
我目前正在尝试编写一个脚本,该脚本逐行读取文本文件,并将所有出现特定str
的行(例如(如果该行具有字符串'apple'
或'Hello World'
)传输到新的文本文件。
fpath = open('Redshift_twb.txt', 'r')
lines = fpath.readlines()
fpath_write = open('Redshift_new.txt', 'w+')
print(lines[0:10])
fpath_write.write(lines[0:10])
fpath.close()
fpath_write.close()
目前,我只设置了基础知识,但我被卡住了,因为当我使用.readlines()
它会将所有行添加到单独索引的列表中。 然后当我尝试写回一个新文件时,我收到一条错误消息:
fpath_write.write(lines[0:10])
TypeError: write() argument must be str, not list
因为您不能在list
上使用函数.write()
。
我知道这是一个两部分的问题,但任何帮助都将不胜感激。
\\n
join
其行 - 将单个字符串拼接在一起fpath = open('Redshift_twb.txt', 'r')
lines = fpath.readlines()
fpath_write = open('Redshift_new.txt', 'w+')
print(lines[0:10])
# filter the list; with the string 'apple'
# replace 'apple' with whatever string you want to find
out_lines = [line for line in lines if 'apple' in line]
# Join the lines into a single string
output = '\n'.join(out_lines)
# write it
fpath_write.write(output)
fpath.close()
fpath_write.close()
用这个fpath_write.write(''.join(line for line in lines[0:10] if 'content1' in line))
替换你的fpath_write.write(lines[0:10])
fpath_write.write(''.join(line for line in lines[0:10] if 'content1' in line))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.