python打开扩展名为“.dta”的目录中的所有纯文本文件,并向cs写入行

2024-05-08 15:55:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多纯文本配置文件(.dta),它们分布在27个子目录中。我正在尝试将它们中的一些信息解析为一个更易于使用的通用文档。在

到目前为止,我已经:

import linecache
import csv
import os

csvout = csv.writer(open("dtaCompile.csv","wb"))

directory = os.path.join("c:\\","DirectKey")
for root,dirs,files in os.walk(directory):
for file in files:
    if file.endswith(".DTA"):
        f=open(file,'r')

        lines = f.readlines()
        description = lines[1]
        articleCode = lines[2]
        OS = lines[25]
        SMBIOS = lines[32]
        pnpID = lines[34]
        cmdLine = lines[28]
        csvout.writerow([SMBIOS, description, articleCode, pnpID, OS, cmdLine])
        f.close()

我得到以下错误:

^{pr2}$

Tags: csvinimportforosfilesdescriptionopen
3条回答

而不是:

f=open(file,'r')

尝试:

^{pr2}$

而不是

    f=open(file,'r')

你的试用需求

^{pr2}$

文件只是文件的名称,并没有说明它的路径。你必须使用os.path.join操作系统用不同的组件来创建完整的路径

if file.endswith(".DTA"):
    file = os.path.join(directory, root, file)

相关问题 更多 >