python修改文件内容_使用Python修改文件内容后如何保存更改

您似乎误解了代码的作用。我们一行一行地走with open("original.txt", "r+") as file: # open a file for reading

lines = file.readlines() # read the contents into a list of lines

print(lines) # print the whole file

for number, item in enumerate(lines): # iterate over lines

if testStr in item:

i = number +2

print(i) #test

lines.insert(i, newLine) # insert lines into the list

print(lines) #test

break # get out of the look

file.close() # not needed, with statement takes care of closing

您没有修改文件。将文件读入字符串列表并修改列表。要修改实际的文件,您需要打开它进行写入并将列表写回其中。在代码末尾这样做可能会奏效

^{pr2}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值