【问题标题】:I'm trying to change a line of a file in Python, but the content just disappears我正在尝试在 Python 中更改文件的一行,但内容就消失了
【发布时间】:2021-05-27 19:03:54
【问题描述】:

首先这是我的 oode:

c = open('Tasks//Task_Counter.txt', 'r+')
okay = c.read().splitlines()

which_task = int(okay[0])
this_task = which_task + 1 

which_port = int(okay[1])
this_port = which_port + 1

c.truncate(0)
c.close()

c = open('Tasks//Task_Counter.txt', 'r+')
okay = c.read().splitlines()

c.write(str(this_task))
c.write("\n")
c.write(str(this_port))

c.close()

f = open("Tasks//task"+ str(this_task) +".py","w+")
q = open('Tasks//task_maker.py', 'r+')


for line in q:
    f.write(line)    

new_file_lines = f.read().splitlines()

line13 = new_file_lines[12]

line13.write("this_browser = "+str(this_port))

q.close()
f.close()

基本上,第一部分是创建一个包含“task_maker.py”内容的新 Python 文件。这工作得很好。唯一的问题是,当我尝试更改新创建的 Python 文件的任何内容时,它的内容就会消失。即使再次关闭和打开它也会导致该问题。 谁能解决这个问题?

【问题讨论】:

  • 不断重写文本文件效率低下且脆弱。尝试使用 SQLite 之类的简单数据库。

标签: python file text text-files


【解决方案1】:

你可以用append代替write

line13.append("this_browser = "+str(this_port))

【讨论】:

  • 当我尝试它给我错误:line13 = new_file_lines[12] IndexError: list index out of range
  • line13 = new_file_lines[:12]
  • 添加列表切片 [:12]
  • 试过了。不会给我一个错误,但它只是没有将文本添加到第 13 行。
猜你喜欢
  • 1970-01-01
  • 2011-08-25
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2013-02-19
相关资源
最近更新 更多