Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python从文本文件中读取一系列数字并写入新行?_Python - Fatal编程技术网

如何使用python从文本文件中读取一系列数字并写入新行?

如何使用python从文本文件中读取一系列数字并写入新行?,python,Python,我是python的初学者,正在使用python 2.7。我有一个文本文件如下 123455555511222545566332221565656532232354354353545465656545454541245587 我想读这一行,把每一个数字写在新的一行 预期产出如下: 1 2 3 4 5 5 5 5 5 5 1 1 2 2 2 5 4 5 5 6 6 3 2 2 2 1 . . . . 7 如何将其读写到另一个文件?您可以循环使用此字符串中的所有字符 line = "123455

我是python的初学者,正在使用python 2.7。我有一个文本文件如下

123455555511222545566332221565656532232354354353545465656545454541245587
我想读这一行,把每一个数字写在新的一行

预期产出如下:

1
2
3
4
5
5
5
5
5
5
1
1
2
2
2
5
4
5
5
6
6
3
2
2
2
1 
.
.
.
.
7

如何将其读写到另一个文件?

您可以循环使用此字符串中的所有字符

line = "123455555511222545566332221565656532232354354353545465656545454541245587"
for c in line:
    print(c)
list.txt:

123455555511222545566332221565656532232354354353545465656545454541245587
然后:

logFile = "list.txt"

with open(logFile) as f:
    content = f.read()     
for line in content:
    print(line)
输出:

1
2
3
4
5
5
5
5
5
5
1
1
2
2
2
5
4
.
.
.
5
5
8
7
编辑:

output.txt:

1
2
3
4
5
5
5
5
5
5
1
1
2
2
.
.
. 
5
5
8
7

假设您有一个文件
test.txt
,其中包含:

123455555511222545566332221565656532232354354353545465656545454541245587
注意不要在文件末尾出现新行。如果打印时存在,则会有一个空行

with open('test.txt', 'r') as f:
    for b in list(f.readline()):
    print(b)

下面的代码是在另一个文件的新行中写入每个内容

with open('logfile.txt','r') as f1:
    with open('writefile.txt','w')as f2:
        read_data=f1.read()
        for each in read_data:
            f2.write(f'{each} \n')

到目前为止,您尝试了哪些内容,哪些内容没有达到预期效果?如果您可以指定您正在使用的python版本,那就太好了。@EmmanuelArias我正在使用python 2.7.12谢谢,我得到了预期的输出,但是如果我将输出写入另一个文件,它将与输入文件写入相同的内容(像行而不是像列)@HalfarisedPheonix我编辑了答案,添加了将其添加到另一个
txt
文件的功能。
with open('logfile.txt','r') as f1:
    with open('writefile.txt','w')as f2:
        read_data=f1.read()
        for each in read_data:
            f2.write(f'{each} \n')