简体   繁体   English

如何使用python读取目录中的所有文件

[英]How to read all files in a directory using python

I have a directory with lot of text files. 我的目录中有很多文本文件。 I want to read each text file in the directory and perform some kind of search operation. 我想读取目录中的每个文本文件并执行某种搜索操作。 I take directory name as a command line argument. 我将目录名称作为命令行参数。 The error I'm getting is IsADirectoryError . 我收到的错误是IsADirectoryError Is there anyway we can make this work without any other module? 无论如何,我们可以在没有任何其他模块的情况下使这项工作成功吗?

This is my code: 这是我的代码:

a = sys.argv
files = a[1:-1]

for i in files:
    print(i)
    f = open(i,'rb')
    for line in f:
        try:
            for word in line.split():
            '''Rest of code here'''

try this code 试试这个代码

def read_files_from_dir(dirname):
    for _file in os.listdir(dirname):
        with open(os.path.join(dirname,_file), "r") as fp:
            print fp.read() 

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

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