python - 列出目录的所有文件名称到文本文件

标签 python python-3.3

我的代码是这样的,但问题是它只给出了output.txt中的最后一个文件名,而不是所有30个文件名。

import os
path="path I wanted"  
dirList=os.listdir(path)
for filename in dirList:
    print (filename)
    f = open("output1.txt", "w")
    f.write(filename) 
    f.close()

最佳答案

您在每次循环迭代中覆盖该文件。首先打开它:

import os
path="path I wanted"  
dirList=os.listdir(path)
with open("output1.txt", "w") as f:
    for filename in dirList:
        print (filename)
        f.write(filename) 

关于python - 列出目录的所有文件名称到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232906/

相关文章:

python - Reddit 搜索 API 未提供所有结果

Python gevent 我没有看到猴子修补默认文件打开/读/写/关闭,如何在 gevent 异步中制作文件 io

python - 使用 NLTK 无法使用 Unicode 字符标记西类牙语文本?

python - 如何将字符串文件导入列表列表?

python - 关于 python 3.3 的对齐数字

python - Paramiko 在异常后不返回提示(Python 3)

Linux "file"命令的 Python 模拟

python - 如果设置为 null,如何创建具有默认值的 Django 模型字段

python - 什么是IndexError?我不断得到它

python - winfo_x winfo_y 获取坐标