写入文本文件的问题

0 python text file

我在使用python将数据写入文本文件时遇到了一些麻烦.基本上,我想要做的是读取文本文件中的信息,更新读取的文本,并将更新的信息写回同一文本文件.阅读和更新文本很容易,但是当我尝试将更新的文本写回文本文件时遇到了困难.

文本文件非常基本,由三行组成.这里是:

48850

z_merged_shapefiles

EDRN_048850
Run Code Online (Sandbox Code Playgroud)

我使用下面的代码尝试更新它但得到了这个错误: 'file' object has no attribute 'writeline'

这是我使用的代码:

fo = open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "r")

read1 = fo.readline()
read2 = fo.readline()
read3 = fo.readline()

fo.close()

edrn_v = int(read1) + 1
newID = "EDRN_" + str(edrn_v)

fo = open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "w")

fo.writeline(edrn_v)
fo.writeline(read2)
fo.writeline(newID)
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 5

虽然有一个readline没有模拟writeline.

您可以使用a write并附加a '\n'来终止一行

with open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "w") as fo:
    fo.write(edrn_v + '\n')
    fo.write(read2 + '\n')
    fo.write(newID + '\n')
Run Code Online (Sandbox Code Playgroud)

或者将所有变量放入a list并使用writelines.

with open("C:\\Users\\T0015685\\Documents\\Python\\Foo1.txt", "w") as fo:
    fo.writelines([edrn_v, read2, newID])
Run Code Online (Sandbox Code Playgroud)

注意

我正在使用with open语句

with open() as f:
Run Code Online (Sandbox Code Playgroud)

所以,你不必管理openclose自我

f.open()
f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)