Concat /附加到Python中特定行文本文件的末尾

时间:2017-05-07 03:52:05

标签: python

我需要在文本文件的特定行末尾添加一些文本。我目前正在尝试使用类似的方法:

entryList = [5,4,3,8]
dataFile = open("file.txt","a+)
for i in dataFile:
     for j in entryList:
     lines[i] = lines[i].strip()+entryList[j]+" "
dataFile.write(lines[i])

我想在文字后面立即添加数字。

文本文件设置:

it is 
earlier it was 
before that it was 
later it will be 

2 个答案:

答案 0 :(得分:0)

您已经在问题和代码中提到了每一行的特定行。

import fileinput

entryList = [5,4,3,8]

count = 0

for line in fileinput.FileInput('data.txt',inplace=1): print line+str(entryList[count])+" " count+=1

答案 1 :(得分:0)

从同一个文件中读取然后写入并不是一个好主意。我建议根据需要打开它:

entryList = [5,4,3,8]

with open("file.txt", "r") as dataFile:
  # You may want to add '\n' at the end of the format string
  lines = ["{} {} ".format(s.strip(), i) for s,i in zip(dataFile, entryList)]

with open("file.txt", "w") as outFile:
  outFile.writelines(lines)