阅读2个文件,在每行之间添加一些内容

2024-06-16 15:01:25 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

    eeee = input('\nWhat do you want to combine each other with? ')
    first = []
    second = []
    with open('First.txt', 'r') as f:
        for line in f.readlines():
            first.append(line)
    with open('Second.txt', 'r') as f:
        for line in f.readlines():
            second.append(line)
    with open('NewStuff.txt', 'a') as f:
        for thing in first:
            for thing2 in second:
                f.write(thing + str(eeee) + thing2)

我想从FILE1获得第一行,在中间添加一些东西(不管EEEE被输入什么),然后从FILE2打印第一行,然后得到第二行,重复


Tags: intxt密码foraswithlineopen
3条回答

因为您希望str(eeee)中的所有字符串都是second,所以您可以将它添加到该列表所有项目的开头

third = [str(eeee)+i for i in second]

您可以使用^{}openning multiple files尝试类似的方法:

eeee = input('\nWhat do you want to combine each other with? ')


with open('First.txt', 'r') as f1, open('Second.txt', 'r') as f2,open('NewStuff.txt', 'a') as fnew:
    for first, second in zip(f1.readlines(),f2.readlines())
            fnew.write(first.replace('\n','')+' '+ str(eeee)+' '+ second)

您的代码几乎正确,只需更改此部分:

with open('NewStuff.txt', 'a') as f:
    for thing in first:
        for thing2 in second:
            f.write(thing + str(eeee) + thing2)

致:

with open('NewStuff.txt', 'a') as f:
    for thing,thing2 in zip(first,second):
        f.write(thing + str(eeee) + thing2) 

相关问题 更多 >