首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将文件输出写入.csv

将文件输出写入.csv
EN

Stack Overflow用户
提问于 2019-02-08 07:43:29
回答 1查看 725关注 0票数 0

我正在尝试编写一些基本的脚本,以便列出带有.dwg文件的Autocad文件列表,并将其写入.csv文件,稍后我会将该文件导入到Excel中。

我已经在这上面工作了大约两周了。这只是一个简单的脚本,但它要了我的命。我使用的是Python2.7和IDLE和Windows10。

代码语言:javascript
复制
import os, glob, sys
###
###
###We're changing the Current Working Directory to this dir using the 
###os.chdir command

os.chdir(r'h:\\09- DISTRIBUTION\engineer\drft-tmp\355-plg1\EWR 195 - 6018 
Panel Repl\PG1 6018')

###Now we're using glob to find files with .dwg extension
###and we're printing to the IDLE SHELL, which is nice, but I don't want 
this
###HOWEVER, I want to print to a .csv file

files = glob.glob('*.dwg')
for file in glob.glob("*.dwg"):
print(file)



###Let's create a file for the text file

f = open("ListDWG1.txt", "w+")
myfile = open(r'h:\\09- DISTRIBUTION\engineer\drft-tmp\355-plg1\EWR 195 - 
6018 Panel Repl\PG1 6018')

###I'm stuck at this point. How do I get the .csv file created?
###How are we to write a file in .csv format
###So, let's use the for command to loop through the contents of this cwd
EN

Stack Overflow用户

发布于 2019-02-08 07:59:27

您最好导入csv,这是一个用于管理*.csv文件的内置python模块。它有写入器和阅读器功能,还有一个字典解析器,以便在阅读时更好地使用数据。

看看这个:https://realpython.com/python-csv/

编写步骤如下:

代码语言:javascript
复制
with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    employee_writer.writerow(['John Smith', 'Accounting', 'November'])
    employee_writer.writerow(['Erica Meyers', 'IT', 'March'])

和阅读:

代码语言:javascript
复制
import csv

with open('employee_birthday.txt') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print("Column names are", ", ".join(row))
            line_count += 1
        else:
            print(row[0], "works in the", row[1], "department, and was born in", row[2])
            line_count += 1
    print("Processed", line_count, "lines.")

您可以根据自己的需要修改此代码

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54584050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档