【发布时间】:2018-01-13 09:34:49
【问题描述】:
我想为目录中的每个文件分配唯一的变量名。我不知道如何做到这一点。我是 python 新手,所以很抱歉代码很邋遢。
def DataFinder(path, extension):
import os
count = 0
extensions = ['.txt','.csv','.xls','xlsm','xlsx']
allfiles = []
if not extension in extensions:
print('Can\'t read data from this file type.\n','Allowed file types are\n',str(extensions))
else:
#loop through the files
for root, dirs, files in os.walk(path):
for file in files:
#check if the file ends with the extension
if file.endswith(extension):
count+=1
print(str(count)+': '+file)
allfiles.append(file)
if count==0:
print('There are no files with',extension,'extension in this folder.')
return allfiles
如何修改此代码以将变量名称(如 df_number.of.file)分配给每次迭代作为字符串?
谢谢
我的最终目标是为每个文件以唯一的变量名称设置一组 DataFrame 对象,而无需手动创建这些变量。
建议的副本没有回答我的问题,也不适合我。
allfiles = {}
#filter through required data extensions
if not extension in extensions:
print('Can\'t read data from this file type.\n','Allowed file types are\n',str(extensions))
else:
#loop through the files
for root, dirs, files in os.walk(path):
for file in files:
#check if the file ends with the extension
if file.endswith(extension):
#raise counter
count+=1
print(str(count)+': '+file)
allfiles.update({'df'+str(count) : path+file})
按照建议调整代码后,我的输出是字典:
{'df1': 'C:/Users/Bartek/Downloads/First.csv', 'df2': 'C:/Users/Bartek/Downloads/Second.csv', 'df3': 'C:/用户/Bartek/Downloads/Third.csv'}
我之前使用列表实现了类似的事情:
['df_1First.csv', 'df_2Second.csv', 'df_3Third.csv']
但我的确切问题是如何做到这一点:
对于字典中的每个对象: - 创建一个具有连续对象编号的变量
所以这个变量可以作为数据参数传递给 pandas.DataFrame()
我知道这是一个非常糟糕的主意 (http://stupidpythonideas.blogspot.co.uk/2013/05/why-you-dont-want-to-dynamically-create.html),所以你能告诉我使用 dict 的正确方法吗?
非常感谢
【问题讨论】:
-
不要这样做——根据值设置值的名称是不好的编程习惯。相反,请使用字典,其中所需的名称是键。
-
@RoryDaulton 谢谢。请问我该如何提出正确的问题以找到有关为此目的使用字典的答案?
标签: python python-3.6