我想从第二行写入文本文件。
此刻我将数据写入文本文件:
with open("data1.txt", "w") as file:
file.write(str(round(strength, 2)) + "\n")
file.close()
'Strength'as a value(Number)
要从文本文件中读取特定行(在这种情况下为第二行):
with open("data1.txt", "r", encoding="utf-8") as file:
S1 = file.readlines()
S1 = float(S1[1].strip())
file.close()
如何从第二行开始以文件开头:
with open("data1.txt", "w+", encoding="utf-8") as file:
我知道要从文本文件的开头开始写:
file.seek(0)
如何从第二行替换/更改/写入?
您需要先阅读文件:
with open("file.txt", "r") as file:
lines = file.readlines()
然后更改第二行:
lines[1] = str(round(strength, 2)) + "\n"
然后将所有内容写回:
with open("file.txt", "w") as file:
for line in lines:
file.write(line)
[一种方法是,使用file.readline()
读取第一行,使用len(file.readline())
计数第一行中的字符数,然后使用file.seek(len(file.readline()) + 1)
从该位置即下一行开始写入。] >
您可能需要更改+1
,但我尚未对此进行测试。