【问题标题】:Python3.x: TypeError: expected str, bytes or os.PathLike object, not listPython3.x:TypeError:预期的 str、字节或 os.PathLike 对象,而不是列表
【发布时间】:2019-01-13 23:54:33
【问题描述】:

我在一个文件夹中有许多文本文件。每个文本文件都有两个值,它们分别写在不同的行中(使用 .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')

当前遇到以下错误(如下)。关于如何改进/修复代码的任何想法?

  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

【问题讨论】:

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


    【解决方案1】:

    os.walk 返回一个包含 3 项元组的列表,因此您需要在遍历列表时解包这些元组:

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

    请阅读os.walk's documentation了解更多详情。

    【讨论】:

      猜你喜欢
      • 2021-03-05
      • 2017-10-23
      • 2020-07-12
      • 2019-04-11
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多