python 关闭 : only copy part of the file

标签 python shutil

代码是从一个目录中读取xls文件,将其转换为csv文件并复制到另一个目录。

filePath = os.path.join('.', 'attachments')
filePaths = [f for f in os.listdir(filePath) if os.path.isfile(os.path.join(filePath, f)) and f.endswith('.xls')]

for f in filePaths:
    wb = xlrd.open_workbook(os.path.join(filePath, f))
    sheet = wb.sheet_by_index(0)
    filename = f + '.csv'
    fp = open(os.path.join(filePath, filename), 'wb')
    wr = csv.writer(fp, quoting=csv.QUOTE_ALL)
    for rownum in xrange(sheet.nrows):
       wr.writerow(sheet.row_values(rownum))
    fp.close

    shutil.copy(os.path.join('.', 'attachments', filename), new_directory)

结果是: xls文件已成功转换为csv文件,但在new_directory中,复制的文件仅包含csv文件的部分内容。

例如,原始 csv 文件有 30 行,但复制的文件中只有 17 行。知道为什么会发生这种情况吗?

最佳答案

这是你的问题:

fp.close

您需要调用 close 方法,而不仅仅是将其作为方法引用。所以:

fp.close()

但是,如果您使用 with 语句,而不是试图弄清楚在哪里显式关闭所有内容,这将使您的生活更轻松:

with open(os.path.join(filePath, filename), 'wb') as fp:
    wr = csv.writer(fp, quoting=csv.QUOTE_ALL)
    for rownum in xrange(sheet.nrows):
        wr.writerow(sheet.row_values(rownum))

关于 python 关闭 : only copy part of the file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18110595/

相关文章:

python - 比较两个 1's & 0' s 的大列表并返回差异计数/百分比的最快方法是什么?

python - 如何修复文件移动脚本读取文件名时出现 FileNotFoundError 错误?

python - 有没有办法在 Python 中快速 move 许多文件?

python移动文件夹内容而不移动源文件夹

python - 文件夹被解释为文件

python - shutil.rmtree : FileNotFoundError: [Errno 2] No such file or directory: '._xxx'

python - 检查变量之一是否设置为无

python - 编辑距 ionic 串

python - 使用 sudo 使用 python 创建文件使其所有者成为 root

python - 加入 sqlalchemy 的混合属性