如何使用python写入输出的txt文件?

2024-10-01 02:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我扫描了我的文件夹,然后把它打印到我的文本文件中,但我不知道为什么它只给我一个输出,而这个输出是最后一个namefile

import zipfile
import os

def out_fun():  
    for x in os.listdir('C:\Users\Guest\Desktop\OJT\scanner\samples_raw'):
        print x
    return x
output = out_fun()
file = open("result_vsdt.txt","w")
file.write(output)
file.close()

我的txt文件中的唯一输出是:

fe8c341de79168a1254154f4e4403857c6e79c46

必须是:

ed64498d29f40ccc07c7fbfa2a0a05e29763f5e2 ed66e83ae790873fd92fef146a2b70e5597792ee ef2f8d90ebae12c015ffea41252d5e25055b16c6 f4b8b762feb426de46a0d19b86f31173e0e77c2e f4d0cc44a8018c807b9b1865ce2dd70f027d2ceb f6c9b393b5148e45138f724cebf5b1e2fd8d9bc7 fa2229ef95b9e45e881ac27004c2a90f6c6e0947 fac66887402b4ac4a39696f3f8830a6ec34585be fcbbfeb67cd2902de545fb159b0eed7343aeb502 fe5babc1e4f11e205457f2ec616f117fd4f4e326 fe8c341de79168a1254154f4e4403857c6e79c46


Tags: inimporttxt文件夹foroutputosdef
3条回答

为什么只将最后一个文件的名称写入结果文件?你知道吗

因为当x的每个值都在out_fun函数中打印时,实际上只返回最后一个值。你需要把其他的放在某个地方,然后把它们放回原处。你知道吗

如何返回所有内容?你知道吗

创建一个名为output的字符串,将x的每个值附加到该字符串上,然后返回:

import os

def out_fun():  
    output = ''
    for x in os.listdir('C:\Users\Guest\Desktop\OJT\scanner\samples_raw'):
        print x
        output += x + '\n'
    return output

with file = open("result_vsdt.txt","w"):
    file.write(out_fun())

'\n'是新行字符。这使得舒尔,每一个文件名都在一条新的线上。你知道吗

for循环将遍历文件并以最后一个文件结束。也就是说,x永远是你的最后一个文件。 如果要返回所有文件,需要创建一个列表并将所有文件保存在那里,如下所示:

def out_fun():  
    array = [""]
    for x in os.listdir('C:\Users\Guest\Desktop\OJT\scanner\samples_raw'):
        array.append(x)
    return '\n'.join(array)

试试看,这样更好一点,占用的内存更少,而且您不需要在函数中创建列表或加载所有文件内容:

import zipfile
import os

def out_fun():  
    for x in os.listdir('C:\Users\Guest\Desktop\OJT\scanner\samples_raw'):
        yield x

file = open("result_vsdt.txt","w")
for line in out_fun():
    file.write(line + '\n')
file.close()

编辑:
打开文件时最好使用with,如下所示:

with open("result_vsdt.txt","w") as file:
    for line in out_fun():
        file.write(line + '\n')

它将自动关闭文件。你知道吗

相关问题 更多 >