首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pj.py-将所有文件名从一个程序(dir.py)导入到另一个程序( Python )。但是存储在目录中的文件名会列出两次

Pj.py-将所有文件名从一个程序(dir.py)导入到另一个程序( Python )。但是存储在目录中的文件名会列出两次
EN

Stack Overflow用户
提问于 2015-01-04 16:35:13
回答 1查看 53关注 0票数 0

将所有文件名从一个程序(dir.py)导入到另一个程序(pj.py)。但是从dir.py传递到pj.py的文件名是两次而不是一次。

这是dir.py程序-

代码语言:javascript
复制
#!/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程序中-

代码语言:javascript
复制
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)

当我打印它时,它显示了以下内容:

代码语言:javascript
复制
['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']

它给了我两个数组而不是一个,因此我的文件被处理了两次。

请帮我输入一些信息,告诉我哪里出了问题。

EN

回答 1

Stack Overflow用户

发布于 2015-01-04 16:46:07

你有几个问题:

  1. 您将在每个循环迭代中打印列表。
  2. 您将在每个循环迭代中调用pj.py文件。
  3. 您传递的不是文件的完整路径,而是文件名。
  4. 您已将文件命名为dir.py,这是内置函数的名称。

首先,您应该使用glob,并在您的文件中创建一个列出目录的方法,然后在其他程序中调用此方法,而不是使用execfile

在一个文件中,我们将其命名为list_excel.py,您可以使用如下代码:

代码语言:javascript
复制
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.pypj.py在同一目录中):

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27763827

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档