代码是从一个目录中读取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/