簡體   English   中英

如何逐個打開多個文件並在Python中打印內容

[英]How to open multiple files one-by-one and print the contents in Python

我正在研究一個逐個讀取多個文件(從單個文件中的文件名)的函數。 我設置了獲取文件中文件名數量的方法,但我不確定在循環序列中應該使用什么。 這是我現在的位置:

with open('userdata/addedfiles', 'r') as read_files:
        number_of_files = sum(1 for _ in read_files)

    print(number_of_files, "files added")
    print("File contents: \n")

    # get individual filenames in file and
    # read them one by one

    for x in range(number_of_files):
        # hmm...

關於在這里使用什么的任何建議? 謝謝。

你有正確的想法,但是對於你當前的設置,你將在輸入文件中循環幾次,超過必要的數量。 讓我們嘗試這樣的事情:

with open('userdata/addedfiles', 'r') as read_files:
    file_lines = read_files.readlines()
    # print the length of the lines from the input file
    print(len(file_lines), "files added")

    # do stuff per line (which in your case is a file name)
    for file_name in file_lines:
        print(file_name.strip())

我不確定你想要實現什么,但下面的代碼將打開userdata/addedfiles/所有文件,並userdata/addedfiles/打印文件名和內容。

你可以使用glob

import glob
for file in glob.glob("userdata/addedfiles/*"):
    print file
    myfile = open(file,"r")
    lines = myfile.readlines()
    for line in lines:
         print line.strip();

不清楚你為什么需要獲取主文件中的文件數量,但為什么不只是:

with open('userdata/addedfiles', 'r') as read_files:
    for infile in read_files:
        with open(infile) as infile2:
             # Do something with contents

暫無
暫無

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

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