How to make a path that has variable input in the middle read in a input file in python

瘦欲@ 提交于 2019-12-11 17:56:53

问题


This should be pretty easy, not sure why I can't get it to work. I am trying to import a ton of .txt files as part of a larger process like so:

    path = "C:/Users/A/B/"

    with open(path + "*full.txt","r") as f:
        contents =f.read()
        print(contents)  

I am just trying to import all .txt files (there are a ton of them) in this folder path, when I do this I get:

OSError: [Errno 22] Invalid argument: 

There are strings in the middle that are different between each file hence the * before the full it lists the path after argument (for privacy reasons I will leave it out but you get the point) and I know that the path is correct, why is it giving me this error?


回答1:


You can't use * in open(). open() can open only one file with exact name.

You have to get all names in directory and use for-loop to open every file separatelly.

With glob.glob():

import glob

path = "C:/Users/A/B/"

for fullname in glob.glob( path + "*full.txt" ):
    with open(fullname, "r") as f:
        contents = f.read()
        print(contents)

With os.listdir():

import os

path = "C:/Users/A/B/"

for name in os.listdir(path):
    if name.endswith("full.txt"):
        fullname = os.path.join(path, name):
        with open(fullname, "r") as f:
            contents = f.read()
            print(contents)



回答2:


When you type a wildcard at the command prompt like so:

cat /some/dir/*full.txt

The shell performs the wildcard expansion and passes the full actual filename to cat.

But Python doesn't do that; there is no shell. When you get to the point of calling open(), you must use the full real filename.

Try looking at the glob module.



来源:https://stackoverflow.com/questions/57223075/how-to-make-a-path-that-has-variable-input-in-the-middle-read-in-a-input-file-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!