您如何读取文件,然后在txt中将整数输出为'1'

问题描述 投票:-3回答:1

我正在尝试打开一个txt文件eg.txt包含

    1234 then return '1','2','3','4'
    5678             '5','6','7','8'

我已经尝试过使用str将它们加在一起,好像``似乎消失了。

 with open('a.txt') as if1:
    for everyline in if1:
        everylineactual = everyline.rstrip('\n')
        for i in everylineactual:
            a= str(i)
            with open('b.txt','a') as of:
                of.write('"')
                of.write(a)
python
1个回答
0
投票

这应该可以解决您的问题。

输入文件:

1234
5678

代码:

with open('a.txt') as if1:
    for everyline in if1:
        everylineactual = everyline.rstrip('\n')
        everylineactual = "','".join(everylineactual)
        everylineactual = f"'{everylineactual}'\n"
        with open('b.txt','a') as of:
            of.write(everylineactual)

输出文件:

'1','2','3','4'
'5','6','7','8'
© www.soinside.com 2019 - 2024. All rights reserved.