将所有文件名从一个程序(dir.py)导入到另一个程序(pj.py)。但是从dir.py传递到pj.py的文件名是两次而不是一次。
这是dir.py程序-
#!/usr/bin/python
import os
root = 'C:/Users/Desktop/Files/test' ##THE PATH IS WHERE ALL EXCEL DATASHEETS ARE STORED.
# Traverse directory, and list files
for files in os.listdir(root):
#Call the main python program
file_location = os.path.join(root, files)
print files
execfile('C:/Users/Desktop/pj.py')
#THIS PATH REFERS TO THE DIRECTORY WHERE THE PYTHON PROGRAM pj.py is going to manipulate the datasheet. It takes the file name from dir.py as a parameter.现在,在pj.py程序中-
import xlrd
import re
from dir import file_location
#The file location is passed as a argument from first program. Worksheet is open
workbook = xlrd.open_workbook(file_location)当我打印它时,它显示了以下内容:
['Disambiguation_Version 1t_Bo Zheng.xlsx', 'Disambiguation_Version 1t_Jun Xi.xlsx', 'Disambiguation_Version 1_Samantha_26nov2014.xlsx', 'Disambiguation_Version 1_Xin Hua_entiredata.xlsx', 'Disambiguation_Version 2o_Maximus.xlsx', 'Disambiguation_Version 2o_theresa.xlsx', 'Disambiguation_Version 2t_Cheng Ai.xlsx', 'Disambiguation_Version 2_Summer_entiredata.xlsx', 'Disambiguation_Version 2_Tricia.xlsx', 'Disambiguation_Version 3_Emily_entiredataset.xlsx', 'test']
['Disambiguation_Version 1_Samantha_26nov2014.xlsx', 'Disambiguation_Version 1_Xin Hua_entiredata.xlsx', 'Disambiguation_Version 2t_Cheng Ai.xlsx']它给了我两个数组而不是一个,因此我的文件被处理了两次。
请帮我输入一些信息,告诉我哪里出了问题。
发布于 2015-01-04 16:46:07
你有几个问题:
pj.py文件。dir.py,这是内置函数的名称。首先,您应该使用glob,并在您的文件中创建一个列出目录的方法,然后在其他程序中调用此方法,而不是使用execfile
在一个文件中,我们将其命名为list_excel.py,您可以使用如下代码:
import glob
import os
def get_excel_files(directory=None):
for filename in glob.iglob(os.path.join(directory, '*.xls?')):
yield filename在pj.py中,您可以导入此函数(请确保list_excel.py和pj.py在同一目录中):
from list_excel import get_excel_files
root = 'C:/Users/Desktop/Files/test'
for file_location in get_excel_files(root):
workbook = xlrd.open_workbook(file_location)https://stackoverflow.com/questions/27763827
复制相似问题