简体   繁体   English

使用python读取目录中的多个文件

[英]Reading in multiple files in directory using python

I'm trying to open each file from a directory and print the contents, so I have a code as such: 我试图从目录中打开每个文件并打印内容,所以我有这样的代码:

import os, sys

def printFiles(dir):
    os.chdir(dir)
    for f in os.listdir(dir):
        myFile = open(f,'r')
        lines = myFile.read()
        print lines
        myFile.close()

printFiles(sys.argv[1])

The program runs, but the problem here is that it is only printing one of the contents of the file, probably the last file that it has read. 该程序运行,但是这里的问题是它仅打印文件内容之一,可能是它读取的最后一个文件。 Does this have something to do with the open() function? 这与open()函数有关吗?

Edit: added last line that takes in sys.argv. 编辑:添加了最后一行,需要sys.argv。 That's the whole code, and it still only prints the last file. 这就是整个代码,它仍然只打印最后一个文件。

There is problem with directory and file paths. 目录和文件路径有问题。

Option 1 - chdir: 选项1-chdir:

def printFiles(dir):
    os.chdir(dir)
    for f in os.listdir('.'):
        myFile = open(f,'r')
        # ...

Option 2 - computing full path: 选项2-计算完整路径:

def printFiles(dir):
    # no chdir here
    for f in os.listdir(dir):
        myFile = open(os.path.join(dir, f), 'r')
        # ...

But you are combining both options - that's wrong. 但是您同时使用了这两种选择-错了。

This is why I prefer pathlib.Path - it's much simpler: 这就是为什么我更喜欢pathlib.Path -它要简单得多:

from pathlib import Path

def printFiles(dir):
    dir = Path(dir)
    for f in dir.iterdir():
        myFile = f.open()
        # ...

The code itself certainly should print the contents of every file. 代码本身当然应该打印每个文件的内容。 However, if you supply a local path and not a global path it will not work. 但是,如果您提供本地路径而不是全局路径,则将无法使用。

For example, imagine you have the following folder structure: 例如,假设您具有以下文件夹结构:

./a
./a/x.txt
./a/y.txt
./a/a
./a/a/x.txt 

If you now run 如果现在运行

printFiles('a')

you will only get the contents of x.txt , because os.listdir will be executed from within a , and will list the contents of the internal a/a folder, which only has x.txt . 您只会得到x.txt的内容,因为os.listdir将从a内部执行,并将列出内部a / a文件夹的内容,该文件夹仅包含x.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM