2

我目前正在执行此任务并陷入困境。请给我你的建议。我在下面写的代码,它只返回来自多个文件夹的 .txt 文件名,而我想打印出每个 .txt 文件的内容并保存在 excel 中的不同行中。每个 .txt 文件的内容都是数字。

import os, glob,xlwt
#create workbook and worksheet
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
path= 'E:\Cag\Data'
row = 0
for dir,subdir,files in os.walk(path):
    for file in files:
        if glob.fnmatch.fnmatch(file, '*.txt'):
            L = file.strip()
            sheet.write(row,5,L)
            row += 1
wbk.save('read_all_txt_in_folders.xls')
print 'success'
4

2 回答 2

2

好吧,您会看到文件名,因为您编写了它们。L包含文件名。(而且L = file.strip()对我来说似乎没有必要。)

如果要写入文件内容,则应改为L = open(os.path.join(dir, file), "r").read().

于 2011-09-30T06:54:13.237 回答
2

如果要写入文件内容,则应改为

with open(os.path.join(dir, file), "r") as source:
    L= source.read()

这可以确保在您阅读完文件后实际关闭文件。这会释放系统资源。

于 2011-09-30T10:09:56.323 回答