所以我扫描了我的文件夹,然后把它打印到我的文本文件中,但我不知道为什么它只给我一个输出,而这个输出是最后一个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
为什么只将最后一个文件的名称写入结果文件?你知道吗
因为当
x
的每个值都在out_fun
函数中打印时,实际上只返回最后一个值。你需要把其他的放在某个地方,然后把它们放回原处。你知道吗如何返回所有内容?你知道吗
创建一个名为
output
的字符串,将x
的每个值附加到该字符串上,然后返回:'\n'
是新行字符。这使得舒尔,每一个文件名都在一条新的线上。你知道吗for循环将遍历文件并以最后一个文件结束。也就是说,x永远是你的最后一个文件。 如果要返回所有文件,需要创建一个列表并将所有文件保存在那里,如下所示:
试试看,这样更好一点,占用的内存更少,而且您不需要在函数中创建列表或加载所有文件内容:
编辑:
打开文件时最好使用
with
,如下所示:它将自动关闭文件。你知道吗
相关问题 更多 >
编程相关推荐