如何使在中间具有可变输入的路径在python的输入文件中读取 [英] How to make a path that has variable input in the middle read in a input file in python
问题描述
这应该很容易,不确定为什么我无法使它正常工作.我正在尝试导入大量的.txt文件,作为更大的过程的一部分,例如:
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)
我只是尝试导入此文件夹路径中的所有.txt文件(其中有很多),当我这样做时,我会得到:
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?
推荐答案
您不能在open()
中使用*
. open()
只能打开一个名称完全相同的文件.
You can't use *
in open()
. open()
can open only one file with exact name.
您必须获取目录中的所有名称,并使用for
-loop单独打开每个文件.
You have to get all names in directory and use for
-loop to open every file separatelly.
使用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)
使用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)
这篇关于如何使在中间具有可变输入的路径在python的输入文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!