![](/img/trans.png)
[英]Python: I have a list of words, and want to check the number of occurrences of those words in each line in a file
[英]I want to replace words from a file by the line no using python i have a list of line no?
如果我有一个像这样的文件:
Flower
Magnet
5001
100
0
我有一个包含行号的列表,必须更改。
list =[2,3]
我如何使用python做到这一点,我期望的输出是:
Flower
Most
Most
100
0
我尝试过的代码:
f = open("your_file.txt","r")
line = f.readlines()[2]
print(line)
if line=="5001":
print "yes"
else:
print "no"
但无法匹配。 我想覆盖正在读取的文件
您可以简单地遍历必须在文件中替换的索引列表(我的原始答案不必要地遍历文件中的所有行):
with open('test.txt') as f:
data = f.read().splitlines()
replace = {1,2}
for i in replace:
data[i] = 'Most'
print('\n'.join(data))
输出:
Flower
Most
Most
100
0
要覆盖使用替换文件打开的文件,可以使用以下命令:
with open('test.txt', 'r+') as f:
data = f.read().splitlines()
replace = {1,2}
for i in replace:
data[i] = 'Most'
f.seek(0)
f.write('\n'.join(data))
f.truncate()
您遇到此问题的原因是,当您从以python打开的文件中提取一行时,您还会在末尾获得换行符( \\n
)。 要解决此问题,可以使用string.strip()函数,该函数将自动删除这些字符。
例如。
f = open("your_file.txt","r")
line = f.readlines()
lineToCheck = line[2].strip()
if(lineToCheck == "5001"):
print("yes")
else:
print("no")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.