python - 循环打印多行(按预期)但只将一行写入文件
问题描述
循环读取目录中的所有文本文件并打印每个文本文件第一行的值(如预期的那样),但只将一行写入文件。
我使用 for 和 while 循环尝试了几种循环变体,但我认为我可能做错了。我被甩了,因为它打印了正确的输出(几行),但只写了一行。
# this program reads the files in this directory and gets the value in the first line of each text file
# it groups them by the first two numbers of their filename
import glob
# get list of all text files in directory
path = "./*.txt"
txt_files = glob.glob(path)
# these are the groups I need to sort the results by
a1 = "10"
a2 = "20"
b1 = "30"
c1 = "40"
# list of files is in txt_files
for fileName in txt_files:
# get the two digits from the filename to group the files
device = fileName[2:4]
# if the file name's first two digits (device) match the variable, open the file and get the value in the first line
if device == a1:
file = open(fileName)
line = file.readline()
# then, write that first line's value to the usage.txt file
print(device + "_" + line)
fileU = open("usage.txt", 'w')
fileU.write(device + "_" + line + "\n")
file.close()
# if the file name's first two digits = 20, proceed
elif device == a2:
# open the text file and get the value of the first line
file = open(fileName)
line = file.readline()
print(device + "_" + line)
fileU = open("usage.txt", 'w')
fileU.write(device + "_" + line + "\n")
file.close()
# if the file name's first two digits = 30, proceed
elif device == b1:
file = open(fileName)
line = file.readline()
print(device + "_" + line)
fileU = open("usage.txt", 'w')
fileU.write(device + "_" + line + "\n")
file.close()
预期的结果将usage.txt
显示与控制台中打印的相同的输出。
usage.txt
将只有一行:30_33
控制台将打印所有行:
10_36
10_36
20_58
20_0
20_58
30_33
30_33
进程以退出代码 0 结束
解决方案
您正在打开并截断文件,使用以下命令打开append
:
由于您每次循环时都打开文件,并且您没有使用a
,因此每次循环都会截断文件,因此每个循环都会编写一个新的 1 行文件。
fileU = open("usage.txt", 'a')
推荐阅读
- wordpress - 如何将占位符图标放入联系表格 7?
- html - HTML 输入模式属性
- node.js - 由于安装位置已被删除,无法全局卸载此 node.js 包
- c# - 在列表框中选择项目时尝试显示数据集中行的所有值
- python - 如何强制 Python (EMCEE) 在先前定义的范围之间精确移动
- laravel - 如何在不同的 Laravel 控制器中重用自定义函数?
- spring-mvc - java.lang.IllegalStateException:没有为 servlet 请求找到匹配的处理程序方法
- php - Codeigniter - 使用 MySql 从具有多个重复 MaxDate/time 的元表中获取数据
- unit-testing - 我们如何衡量 100 个并发用户的 Azure 搜索建议 API 的性能?
- lora - 一个通道可以连接多少个节点?