我有这样的剧本:
f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
if a ==58:
print (line)
line1 = "google.ca"
f.write(line1)
print line
a = a+1
f.close()我想保存我的文件,但只想将第58行写的内容更改为"google.ca“,然后使用linux: mint-17.2保存它。
发布于 2015-09-11 02:10:50
# Read data from file
with open('yourfile.txt', 'r') as file:
# read all line in the file to data array
data = file.readlines()
# change data on line 58 (array start from 0)
data[57] = 'Data you need to change'
# Write data back
with open('yourfile.txt', 'w') as file:
file.writelines(data)发布于 2015-09-11 01:39:34
您需要决定是编写一个新文件(使用打印)还是更改旧文件(使用r+模式和f.write)。如果你写了一个新的文件,你可能会感到最快乐。
发布于 2015-09-11 01:47:03
dataRead = []
f = open("/ggg/darr/file/", "r+")
a = 0
for line in f:
if a == 58:
line = "google.ca"
dataRead.append(line)
a = a+1
f.close()
f2 = open("/some/new/file","w")
for line in dataRead:
f2.write(line)
f2.close()https://stackoverflow.com/questions/32513610
复制相似问题