如何读取文件夹中的文本文件并保存在Excel文件中

时间:2018-08-06 23:14:30

标签: excel python-3.x operating-system xlwt

我在一个文件夹中有许多文本文件。每个文本文件都有两个分别写在不同行中的值(在.write函数中使用\ n \)。看起来如下。

0.907831
0.992549

我想创建一个主excel文件,该文件将文本文件中的所有值组合在一起(而不是手动输入)。

所需的输出如下所示。

'Filename' 0.907831 0.992549

到目前为止,我有以下代码。

import xlwt
import os
import fnmatch

path='Z:\Data\13-output'
wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
row = 0


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

wbk.save('all_values_in_txt.xls')

它会生成名为“ all_values_in_txt.xls”的excel文件。但是,excel工作表为空白。关于如何改进/修复代码的任何想法吗?

编辑1(通过将fnmatch更改为fnmatch.fnmatch进行修复):我意识到我遇到了以下错误,if fnmatch(file, '*.txt'): TypeError: 'module' object is not callable

编辑2:我现在遇到新的错误

  File "<ipython-input-81-ddeb0284f378>", line 17, in <module>
    if fnmatch.fnmatch(file, '*.txt'):

  File "C:\Users\JohnDoe\Anaconda3\lib\fnmatch.py", line 34, in fnmatch
    name = os.path.normcase(name)

  File "C:\Users\JohnDoe\Anaconda3\lib\ntpath.py", line 48, in normcase
    s = os.fspath(s)

TypeError: expected str, bytes or os.PathLike object, not list

1 个答案:

答案 0 :(得分:0)

仅基于一些非常轻松的测试,看来它应该对您有用。

Sub ReadFilesIntoActiveSheet()

Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range

' Get a FileSystem object
Set fso = New FileSystemObject

' get the directory you want
Set folder = fso.GetFolder("C:\your_path_here\")

' set the starting point to write the data to
'Set cl = ActiveSheet.Cells(1, 1)
Dim sht As Worksheet
Dim LastRow As Long

Set sh = ActiveSheet

' Loop thru all files in the folder
For Each file In folder.Files
    ' Write file-name
    LastRow = sh.Cells(sh.Rows.Count, "A").End(xlUp).Row + 1
    Range("A" & LastRow).Select
    ActiveCell = file.Name

    ' open the file
    Set txtFile = fso.OpenTextFile(file)

    col = 2
    Do While Not txtFile.AtEndOfStream
        dat = Application.Transpose(Application.Index(Split(txtFile.ReadLine, ","), 1, 0))
        sh.Cells(LastRow, col).Resize(UBound(dat), 1) = dat
        col = col + 1
    Loop

    ' Clean up
    txtFile.Close
    'Range(cl.Address).Offset(1, 0).Select
Next file

Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing

End Sub

注意,您需要从Excel中的一个模块运行它。