将文件输出写入.csv

时间:2019-02-07 23:43:29

标签: python-2.7

我正在尝试编写一些基本脚本来列出并将带有.dwg文件的Autocad文件列表写入.csv文件,然后将其导入Excel。

我已经为此工作了大约2周。这只是一个简单的脚本,但却在杀了我。我使用的是带有IDLE和WINDOWS 10的PYTHON 2.7。

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

1 个答案:

答案 0 :(得分:0)

最好导入csv,这是用于管理* .csv文件的内置python模块。 它具有编写器和读取器功能,还具有Dict解析器,可以在读取时更好地使用数据。

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

编写步骤为:

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'])

阅读:

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.")

您可以根据需要调整此代码