我是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
如何读取和写入其他文件?
答案 0 :(得分:1)
您可以循环浏览此字符串中的所有字符。
line = "123455555511222545566332221565656532232354354353545465656545454541245587"
for c in line:
print(c)
答案 1 :(得分:1)
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
编辑:
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
答案 2 :(得分:0)
假设您有一个文件test.txt
,其中包含:
123455555511222545566332221565656532232354354353545465656545454541245587
请注意不要在文件末尾添加新行。如果在打印时存在,则将有一个空行。
with open('test.txt', 'r') as f:
for b in list(f.readline()):
print(b)
答案 3 :(得分: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')