Цикл печатает несколько строк (как и предполагалось), но записывает только одну строку в файл - PullRequest
0 голосов
/ 09 мая 2019

Цикл читает все текстовые файлы в каталоге и печатает значение из первой строки каждого текстового файла (как и ожидалось), но записывает в файл только одну строку.

Я пробовал несколько вариантов цикла с использованием циклов 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

Ответы [ 2 ]

1 голос
/ 09 мая 2019

Вы воссоздаете файл каждый раз, когда открываете его в цикле. Вы должны открыть его один раз перед циклом.

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()
1 голос
/ 09 мая 2019

Вы открываете и усекаете файл, открываете с помощью append:

Поскольку вы открываете файл каждый раз, когда делаете цикл, и не используете a, вы усекаете файл каждый цикл так,В каждом цикле вы пишете новый 1-строчный файл.

fileU = open("usage.txt", 'a')

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...