问题
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