[英]How to read files with similar names but without writting all the names? python
I have written some code, but I wish to do in a cleverer way, using a for loop to write the names instead. 我已经编写了一些代码,但是我希望以一种更聪明的方式来做,使用for循环来编写名称。
My code is: 我的代码是:
file_name_01 = os.path.join(input_folder_name,'subject101.dat')
file_DF_01 = pd.read_table(file_name_01, ' ', header=None)
file_name_02 = os.path.join(input_folder_name,'subject102.dat')
file_DF_02 = pd.read_table(file_name_02, ' ', header=None)
file_name_03 = os.path.join(input_folder_name,'subject103.dat')
file_DF_03 = pd.read_table(file_name_03, ' ', header=None)
file_name_04 = os.path.join(input_folder_name,'subject104.dat')
But I want something like this: 但是我想要这样的东西:
for(i=0, i<9, i++)
file_name_0%i = os.path.join(input_folder_name,'subject10%i.dat')
file_DF_0%i = pd.read_table(file_name_0%i, ' ', header=None)
I already looked for an answer, but I only found solutions for R, Java and other languages. 我已经在寻找答案了,但是我只找到了针对R,Java和其他语言的解决方案。
I need this in python, if somebody could help me, I will be very happy. 我在python中需要这个,如果有人可以帮助我,我会很高兴。
Instead of dynamically building up variable names, I would use a dict
与其动态地建立变量名,
dict
使用dict
files = dict()
for i in range(9):
file_name = os.path.join(input_folder_name, 'subject10{}'.format(i))
files[file_name] = pd.read_table(file_name , ' ', header=None)
A dictionary seems to be a simple way to handle the relationship of variable names to value. 字典似乎是处理变量名与值之间关系的一种简单方法。
#New dictionary
fileDict = {}
for i in range(1,9):
fileName = "file_name_0"+str(i)
fileDF = "file_DF_0"+str(i)
subjectName = "subject10"+str(i)+".dat"
fileDict[fileName] = os.path.join(input_folder_name,subjectName)
fileDict[fileDF] = pd.read_table(fileDict[fileName], ' ', header=None)
Note: Your example variables start at 1
while your loop starts at 0
注意:您的示例变量从
1
开始,而循环从0
开始
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.