python-在特定位置更新文本文件中的字符串
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-在特定位置更新文本文件中的字符串,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1237字,纯文字阅读大概需要2分钟。
内容图文
![python-在特定位置更新文本文件中的字符串](/upload/InfoBanner/zyjiaocheng/656/7efd64f4fb154eb089388edc7c43408b.jpg)
我想找到一个更好的解决方案来实现以下三个步骤:
>在给定行读取字符串
>更新字符串
>写回更新后的字符串
以下是我的有效代码,但我想知道是否有更好的(简单)解决方案?
new='99999'
f=open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP','r+')
lines=f.readlines()
#the row number we want to update is given, so just load the content
x = lines[95]
print(x)
f.close()
#replace
f1=open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP')
con = f1.read()
print con
con1 = con.replace(x[2:8],new) #only certain columns in this row needs to be updated
print con1
f1.close()
#write
f2 = open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP', 'w')
f2.write(con1)
f2.close()
谢谢!
更新:这次从jtmoulia获得一个想法变得更容易
def replace_line(file_name, line_num, col_s, col_e, text):
lines = open(file_name, 'r').readlines()
temp=lines[line_num]
temp = temp.replace(temp[col_s:col_e],text)
lines[line_num]=temp
out = open(file_name, 'w')
out.writelines(lines)
out.close()
解决方法:
好吧,首先,您不需要每次都重新打开文件并从文件中读取数据. r模式允许您读取和写入给定的文件.
也许像
with open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP', 'r+') as f:
lines = f.readlines()
#... Perform whatever replacement you'd like on lines
f.seek(0)
f.writelines(lines)
另外,Editing specific line in text file in python
内容总结
以上是互联网集市为您收集整理的python-在特定位置更新文本文件中的字符串全部内容,希望文章能够帮你解决python-在特定位置更新文本文件中的字符串所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。