我在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
如何读取和写入该另一个文件?
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
您可以通过这个字符串的所有字符循环。
line = "123455555511222545566332221565656532232354354353545465656545454541245587"
for c in line:
print(c)
假设你有一个文件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')