簡體   English   中英

在python中獲取文本文件中的輸出

[英]Getting The output in a text file in python

我正在編寫代碼以通過我的方法獲取列表中某個文件夾的文件的名稱,我在輸出中公開獲取它。 我想在文本文件中獲取輸出怎么做?

from os import walk

dir_path = r'E://Entertainment//Movies//Hollywood'
res = []

for (dir_path, dir_names, file_names) in walk(dir_path):
    res.extend(file_names)
# print(res)

def f(res):
    yield from res

for x in f(res):
    print(x)

使用具有“寫”模式的with open上下文處理程序並將res列表寫為由換行符連接的字符串:

with open('outpt.txt', 'w') as f:
    f.write('\n'.join(res))

更多信息: https ://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

嘗試:

with open('some_file', 'w') as fh:
    for x in f(res):
        fh.write(f'{x}')

這應該有效:

from os import walk

res = []

dir_path = r'.//Hollywood'
for (dir_path, dir_names, file_names) in walk(dir_path):
    res.extend(file_names)

with open('Hollywood.txt', mode='w') as f:
    for s in res:
        f.write(f'{s}\n')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM