简体   繁体   English

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

[英]Concat/Append to the end of a specific line of text file in Python

I need to add some text to the end of a specific line in a text file. 我需要在文本文件中特定行的末尾添加一些文本。 I'm currently trying to use a method similar to this: 我目前正在尝试使用与此类似的方法:

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])

I'd like to add the numbers immediately following the text. 我想在文字后面立即加上数字。

Text file setup: 文本文件设置:

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

您在问题中提到了特定的行,并且在代码中为每一行编写代码。

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

Reading from and then writing to the same file is not such a good idea. 从同一文件读取然后再写入不是一个好主意。 I suggest opening it as needed: 我建议根据需要打开它:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM