【发布时间】:2016-11-17 17:09:45
【问题描述】:
以下是我的换行功能:
def replace_line(file_name, num, replaced):
f = open(file_name, 'r', encoding='utf-8')
lines = f.readlines()
lines[num] = replaced
f.close()
f = open(file_name, 'w', encoding='utf-8')
f.writelines(lines)
f.close()
我正在使用以下行来运行我的代码:
replace_line('Store.txt', int(line), new)
当我运行我的代码时,它会替换该行,但它也会删除该行之后的所有内容。例如,如果这是我的清单:
【问题讨论】:
-
你能显示
replace_line('Products.txt', int(line[i]), tenminus_str)之前的代码吗? -
为什么同一个文件打开两次?我没有看到 f 在第 1-5 行中使用
-
我不确定我是否遵循您的代码逻辑,您能描述一下您何时要替换该文件中的行吗?
标签: python