如何在python中打印列表中的文本文件输出?

如何在python中打印列表中的文本文件输出?,python,Python,我搜索了stackoverflow,找到了如何从文件夹中获取文件名。 现在我想以txt格式或xlxs格式在文件中打印结果。 你能帮帮我吗。 我是python的新手。 我的代码在下面 from os import listdir from os.path import isfile, join from typing import List onlyfiles: List[str] = [f for f in listdir('D:\\Options') if is

我搜索了stackoverflow,找到了如何从文件夹中获取文件名。 现在我想以txt格式或xlxs格式在文件中打印结果。 你能帮帮我吗。 我是python的新手。 我的代码在下面

    from os import listdir
    from os.path import isfile, join
    from typing import List

   onlyfiles: List[str] = [f for f in listdir('D:\\Options') if isfile(join('D:\\Options',f ))]
   print(onlyfiles)

提前感谢

假设您当前的代码以您希望的方式工作。要写入txt文件,您需要执行以下操作:

with open('you_file.txt', 'w') as f:
    f.write(onlyfiles)

如果已经创建了文件,请使用
'a'
而不是
'w'
,否则它将覆盖内容。

嘿,Vivek,运行此代码时是否出错?
from os import listdir
from os.path import isfile, join
from typing import List

onlyfiles: List[str] = [f for f in listdir('C:\\') if isfile(join('C:\\',f ))]
print(onlyfiles)

with open('result.txt', 'w') as f:
    for file in onlyfiles:
        f.write(f"{file}\n")