循环读取目录中的所有文本文件,并从每个文本文件的第一行打印值(按预期方式),但只向文件写入一行。
我已经尝试过使用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结束的过程
答案 0 :(得分:1)
您正在打开和截断文件,并以append
打开:
由于每次循环都打开文件,并且没有使用a
,因此每次循环都将其截断,因此每次循环都写入一个新的1行文件。
fileU = open("usage.txt", 'a')
答案 1 :(得分:1)
每次在循环中打开文件时,都会重新创建文件。您应该在循环之前将其打开一次。
with open("usage.txt", "w") as fileU:
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.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.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.write(device + "_" + line + "\n")
file.close()