将打印对账单保存到新fi

2024-04-26 18:57:10 发布

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

python新手(应该注意)。对我放松点。在

我写了以下内容来隔离文件的一个非常具体的部分

for line in open('120301.KAP'):
    rec = line.strip()
    if rec.startswith('PLY'):
       print line

输出显示为这样

^{pr2}$

理想情况下,我希望的是输出创建一个带有坐标的CSV文件。(层/1、层/2等不需要停留)。这可行吗?如果没有,至少print语句可以生成一个与KAP文件同名的新textfile吗?在


Tags: 文件inforiflineopenstripprint
3条回答

您可以使用csv模块

import csv  

with open('120301.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    for line in open('120301.KAP'):
        rec = line.strip()
        if rec.startswith('PLY'):
            writer.writerow(rec.split(','))

以类似的方式,csv.reader可以轻松地从输入文件中读取记录。 https://docs.python.org/3/library/csv.html?highlight=csv#module-contents

在python 2.x中,应该以二进制模式打开文件:

^{pr2}$

这是完全可行的!以下是一些文档的链接:https://docs.python.org/2/library/csv.html},用于编写/读取CSV。 你也可以用常规的文件读/写功能制作自己的CSV。在

file = open('data', rw)
output = open('output.csv', w)
file.write('your infos') #add a comma to each string you output?

我想那应该行得通。在

您可以在代码的开头打开文件,然后在打印行后面添加write语句。像这样:

target = open(filename, 'w')
for line in open('120301.KAP'):
rec = line.strip()
if rec.startswith('PLY'):
   print line
   target.write(line)
   target.write("\n") #writes a new line

相关问题 更多 >