簡體   English   中英

Python 3.6:循環遍歷 os.listdir() 中的文件並將其中一些寫入文本文檔

[英]Python 3.6: Looping through files in os.listdir() and writing some of them to a text document

我正在嘗試遍歷一些文件並將 .txt 的文件名寫入另一個 .txt

這段代碼在找到並寫入一個文件的名稱后停止。

我如何讓它寫出其余的名字?

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if file_ext == '.txt':
        with open('file_test.txt', 'r+') as ft:
            ft.write(file_name)

在循環之前只打開一次文件會更有效率。 最好將您的路徑傳遞給os.listdir()不是更改目錄:

import os

with open('file_test.txt', 'w') as ft:
    for f in os.listdir('/users/user/desktop/directory/sub_directory'):
        file_name, file_ext = os.path.splitext(f)
        if file_ext == '.txt':
            ft.write(file_name)

最后,如果你想要一個目錄中的所有“.txt”文件, glob.glob是你的朋友......

您需要以“追加”模式打開目標文件

import os

os.chdir('/users/user/desktop/directory/sub_directory')

for f in os.listdir():
    file_name, file_ext = os.path.splitext(f)
    if file_ext == '.txt':
        with open('file_test.txt', 'a+') as ft:
            ft.write(file_name)

只需將“a+”作為打開函數的第二個參數(其中“a”表示“追加”,“+”表示“如果不存在則創建”)。 我建議您在 write 函數中添加一個分隔符(如“\\n”)以獲得更具可讀性的結果

如果您在 Windows 上,則必須在指定目錄路徑時使用\\\\\\ 並以追加模式寫入文件。看圖

暫無
暫無

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

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