将数据附加到特定行到文件

时间:2016-12-16 07:47:05

标签: python list file

假设我有一个名为text.txt的文件,其中包含数据

    Name
    Age
    City

我在python中有一个列表,我们称之为myList

myList = ['Carl','25','Washingtn']

如何在txt中追加除名称之外的列表的第一项。 我试着做了

try = open('text.txt', 'a')
for i in myList:
 myList.write(i)

但是通过这样做,i的每个值都会出现在txt文件的最后一行,我不知道如何做到这一点所以只需要索引[0]然后开始,依此类推。 非常感谢这里的一些帮助!

2 个答案:

答案 0 :(得分:2)

你可以这样做,如果你得到每一行,你可以在它的末尾添加你喜欢的任何东西并将其重写为一个文件。

# We could keep a counter in mind for getting new elem each time.
count = 0 
myList = ['Carl', '25', 'Washington']
with open('text.txt', 'r') as src:
    with open('dest.txt', 'w') as dest:
       for line in src:
           dest.write('%s%s\n' % (myList[count], line.rstrip('\n')))
           count+=1

此外,您应该检查行数是否与列表中的元素数相匹配,以使其更安全。

答案 1 :(得分:0)

这段代码不对。

try = open('text.txt', 'a')
for i in myList:
 myList.write(i)

从MyList获取项目并再次编写MyList? MyList是list()而不是文件。

所以试试这段代码

myList = ['Carl','25','Washingtn']
result = list()

with open(filepath, "r") as f: # read file
    for line, item in zip(f, myList):
        result.append(line.strip() + " " + str(item) + "\n")

with open(filepath, "w") as f: # write
    f.writelines(''.join(result))

'a'模式将始终位于文件的末尾。

找到更多信息https://docs.python.org/3/library/functions.html#open

相关问题