dar*_*rdi 2 python split file python-3.x
我正在编写遍历文本文件的代码,计算每行中有多少单词,并且无法将结果(每行包含一个数字的多行)放入新的文本文件中.
我的代码:
in_file = open("our_input.txt")
out_file = open("output.txt", "w")
for line in in_file:
line = (str(line)).split()
x = (len(line))
x = str(x)
out_file.write(x)
in_file.close()
out_file.close()
Run Code Online (Sandbox Code Playgroud)
但是我得到的文件将所有数字放在一行中.
如何在我正在制作的文件中分隔它们?
您需要在每行后添加一个新行:
out_file.write(x + '\n')
Run Code Online (Sandbox Code Playgroud)
此外,作为处理文件的更加pythonic方式,您可以使用with语句打开将关闭块末尾文件的文件.
而不是多次赋值并将长度转换为字符串,您可以使用str.format()方法在一行中执行所有这些作业:
with open("our_input.txt") as in_file,open("output.txt", "w") as out_file:
for line in in_file:
out_file.write('{}\n'.format(len(line.split())))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
608 次 |
| 最近记录: |