首页 > 解决方案 > 循环打印多行(按预期)但只将一行写入文件

问题描述

循环读取目录中的所有文本文件并打印每个文本文件第一行的值(如预期的那样),但只将一行写入文件。

我使用 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 结束

标签: pythonpython-3.xloops

解决方案


您正在打开并截断文件,使用以下命令打开append

由于您每次循环时都打开文件,并且您没有使用a,因此每次循环都会截断文件,因此每个循环都会编写一个新的 1 行文件。

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


推荐阅读