如何从一个文本文件中读取序列号和使用Python写新行?

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

我在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

如何读取和写入该另一个文件?

python
4个回答
1
投票

LIST.TXT:

123455555511222545566332221565656532232354354353545465656545454541245587

接着:

logFile = "list.txt"

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

OUTPUT:

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

编辑:

logFile = "list.txt"   

with open(logFile) as f:
    content = f.read()
    with open('output.txt', 'w')as f2:
        for line in content:
            print(line)
            f2.write(line + "\n")

output.txt的:

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

1
投票

您可以通过这个字符串的所有字符循环。

line = "123455555511222545566332221565656532232354354353545465656545454541245587"
for c in line:
    print(c)

0
投票

假设你有一个文件test.txt有:

123455555511222545566332221565656532232354354353545465656545454541245587

请小心,不存在于文件的末尾新行。如果存在,当你打印,你将有一个空行。

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

0
投票

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

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')
© www.soinside.com 2019 - 2024. All rights reserved.