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?
解决方案
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)