如何读取文件夹中所有文本文件的内容并将其作为行复制到一个Excel文件中

4 投票
1 回答
3360 浏览
提问于 2025-04-17 16:23

我在一个文件夹里有100个txt文件(文件夹叫做pos)。我想把所有文件的内容复制过来,然后把它们粘贴成Excel文件中的行。我在StackOverflow上找了一些代码,但它们没有用。请帮帮我。

import xlwt
import os
import glob

wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
path= 'C:\tweet\pos'
row = 0

for files in os.walk(path):
...     for file in files:
...         if fnmatch(file, '*.txt'):
...             L = open(os.path.join( file), "r").read()
...             sheet.write(row,5,L)
...             row += 1
...             

wbk.save('read_all_txt_in_folders.xls')

1 个回答

2

下面这个程序对我来说是有效的。

注意事项:

  • 这里的 '\t' 被当作制表符来处理,而不是路径分隔符。建议使用正斜杠。
  • 需要用到的是 import fnmatchfnmatch.fnmatch(pattern, file)。不需要使用 glob
  • 我需要去掉字符串末尾的换行符。在我的测试中,使用 L[:-1] 就足够了。你可能需要更稳妥的解决方案。
  • os.walk() 返回的是一个元组:(目录, 子目录, 文件)
  • 我把调试信息留在了注释中,希望能对你有帮助。

.

import xlwt
import os
import fnmatch

wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
row = 0

# sheet.write(1, 1, "Hello")

for (dir, dirs, files) in os.walk('.'):
     # print dir
     for file in files:
         # print " ", file
         if fnmatch.fnmatch(file, '*.txt'):
             L = open(os.path.join(dir, file), "r").read()
             # print "  ", L.__repr__()
             a = sheet.write(row,5,L[:-1])
             # sheet.write(row, 4, "hello")
             # print "   ", a
             row += 1

wbk.save('read_all_txt_in_folders.xls')

撰写回答