繁体   English   中英

如何检查文本文件的每一行是否有字符串并将所有出现该单词的行打印到新文本文件中?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM