Цикл читает все текстовые файлы в каталоге и печатает значение из первой строки каждого текстового файла (как и ожидалось), но записывает в файл только одну строку.
Я пробовал несколько вариантов цикла с использованием циклов 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