python - 将新字符串添加到文本文件中特定行的末尾
问题描述
我是 python 新手,因此我无法实施我在网上找到的解决方案来解决我的问题。我正在尝试将特定字符串添加到文本文件的特定行的末尾。据我了解文本命令,如果我不想附加到文件末尾,我必须覆盖文件。所以,我的解决方案如下:
ans = 'test'
numdef = ['H',2]
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
if int(line[0]) == numdef[1]:
if str(line[2]) == numdef[0]:
k = ans+ line
f.write(k)
else:
f.write(line)
基本上,我试图将变量添加ans
到特定行的末尾,即出现在我的列表中的行numdef
。因此,例如,对于
2 H: 4,0 : 在哪里搜索信息 : google
我想
2 H: 4,0 : 在哪里搜索信息 : google test
我也尝试过使用line.insert()
但无济于事。
我知道使用 open 命令的“a”功能在这里不是那么相关和有用,但我没有想法。会喜欢这个代码的提示,或者如果我应该放弃它并重新考虑整个事情。感谢您的时间和建议!
解决方案
尝试这个。如果它满足第一个要求但不满足另一个要求,则您没有 else 案例。
ans = 'test'
numdef = ['H',2]
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
if int(line[0]) == numdef[1] and str(line[2]) == numdef[0]:
k = line.replace('\n','')+ans
f.write(k)
else:
f.write(line)
f.close()
更好的方法:
#initialize variables
ans = 'test'
numdef = ['H',2]
#open file in read mode, add lines into lines
with open(textfile, 'r') as f:
lines=f.readlines()
#open file in write mode, override everything
with open(textfile, 'w') as f:
#in the list comprehension, loop through each line in lines, if both of the conditions are true, then take the line, remove all newlines, and add ans. Otherwise, remove all the newlines and don't add anything. Then combine the list into a string with newlines as separators ('\n'.join), and write this string to the file.
f.write('\n'.join([line.replace('\n','')+ans if int(line[0]) == numdef[1] and str(line[2]) == numdef[0] else line.replace('\n','') for line in lines]))
推荐阅读
- unit-testing - 使用 github.com/jarcoal/httpmock 验证请求正文
- angular - Angular 7中ng-cloak(angularjs)的替代方法是布尔变量而不是对象
- python - 有没有办法在给定点找到多边形?
- android - 有什么方法可以禁用片段上的深层链接?
- javascript - 我们如何将上传的图片src的路径保存在一个文件中
- node.js - NodeJS 本身在 Windows 上保存文件 EBUSY?
- php - foreach() 在文件写入时添加空行
- python - 将 Dask Series 对象转换为时间戳
- google-drive-api - 如何通过 API 将 pptx 文件转换为 Google 幻灯片演示文稿?
- http - 如何使用 golang 服务器检查隐式设置的 http 标头?