在文件Python的特定文本行中附加数据

时间:2019-01-24 23:43:22

标签: python

假设我有一个像这样的文件:

words
words

3245, 3445,
345634, 345678

我想知道是否可以将数据添加到代码的第四行,所以输出是这样的:

words
words

3245, 3445, 67899
345634, 345678

我发现了一个类似的教程:appending a data in a specific line of a text file in Python? 但是问题是我不想使用.startswith,因为文件的开头都不同。

感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

您可以通过执行此操作

# define a function so you can re-use it for writing to other specific lines
def writetoendofline(lines, line_no, append_txt):
    lines[line_no] = lines[line_no].replace('\n', '') + append_txt + '\n'

# open the file in read mode to read the current input to memory
with open('./text', 'r') as txtfile:
    lines = txtfile.readlines()

# in your case, write to line number 4 (remember, index is 3 for 4th line)   
writetoendofline(lines, 3, ' 67899')

# write the edited content back to the file
with open('./text', 'w') as txtfile:
    txtfile.writelines(lines)

# close the file
txtfile.close()