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

时间:2019-11-14 14:57:41

标签: python

我正在尝试打开一个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)

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

这可能有帮助:

    fwrite=open("b.txt","w")
    for line in open("a.txt"):
        fwrite.write("".join(["'" +str(char)+"'," for char in line.strip()]).rstrip("',")+"'\n")
    fwrite.close() 

产生预期的结果