迭代路径+文件名以创建新的文件对象
iterate path + filenames to create new file objects
我正在从事一个需要处理文件的项目,并且:
在一个更复杂的函数中,该函数采用包含项目文件的目录参数
文件名以字符串形式提供
例如。文件 1 = 'file1.json'
文件 2 = 'file2.csv'
文件 3 = 'file3.csv'
我愿意:
- 迭代文件并使用os.path.join创建有效路径
- 迭代这些路径并使用 open() 创建单独的文件对象
我猜是这样的(我知道这是错误的):
for file in [file1, file2, file3]:
file_object{}.format(filename) = open(os.path.join(directory, file),'r')
read contents of file into file object...
不确定这样做是否可行...将不胜感激任何想法
我希望我理解正确你的问题,你不需要完整的目录来读取文件。
from glob import glob
##### get the files without input
files = glob('*.csv')
##or get them from user
files=['file1.json','file2.csv','file3.csv']
rs=[]
for file in files:
with open(file,encoding='utf-8') as f:
rs.append(f.read().splitlines())
rs 的输出:
[ [line1 of file1,line2 of file1,....] , [line1 of file2,line2 of file2,....] ,
[line1 of file3,line2 of file3,....] ... ]
我正在从事一个需要处理文件的项目,并且:
在一个更复杂的函数中,该函数采用包含项目文件的目录参数
文件名以字符串形式提供
例如。文件 1 = 'file1.json' 文件 2 = 'file2.csv' 文件 3 = 'file3.csv'
我愿意:
- 迭代文件并使用os.path.join创建有效路径
- 迭代这些路径并使用 open() 创建单独的文件对象
我猜是这样的(我知道这是错误的):
for file in [file1, file2, file3]:
file_object{}.format(filename) = open(os.path.join(directory, file),'r')
read contents of file into file object...
不确定这样做是否可行...将不胜感激任何想法
我希望我理解正确你的问题,你不需要完整的目录来读取文件。
from glob import glob
##### get the files without input
files = glob('*.csv')
##or get them from user
files=['file1.json','file2.csv','file3.csv']
rs=[]
for file in files:
with open(file,encoding='utf-8') as f:
rs.append(f.read().splitlines())
rs 的输出:
[ [line1 of file1,line2 of file1,....] , [line1 of file2,line2 of file2,....] ,
[line1 of file3,line2 of file3,....] ... ]