2016-08-08 75 views
1

python新增功能(应注意)。在我身上轻松一下。将打印语句保存到新文件中

我写了下面的隔离文件

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

的输出表现为这样

PLY/1,48.107478621032,-69.733975000000 

PLY/2,48.163516399836,-70.032838888053 

PLY/3,48.270000002883,-70.032838888053 

PLY/4,48.270000002883,-69.712824977522 

PLY/5,48.192379262383,-69.711801581207 

PLY/6,48.191666671083,-69.532840015422 

PLY/7,48.033358898628,-69.532840015422 

PLY/8,48.033359033880,-69.733975000000 

PLY/9,48.107478621032,-69.733975000000  

的一个非常具体的部分理想的情况是什么,我希望的是创造一个CSV输出文件与坐标。 (PLY/1,PLY/2等不需要停留)。这是可行的吗?如果没有,至少打印语句是否会生成一个与KAP文件同名的新文本文件?

+1

[如何重定向“打印”输出到使用python文件?(可能的重复http://stackoverflow.com/que stions/7152762 /如何对重定向打印输出到一个文件,使用的Python) –

+0

这是相当不同的,看我的问题的全部 – dpalm

回答

1

您可以使用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

编辑#1

在蟒蛇2.x的,你应该以二进制模式打开文件:

import csv 

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

类型错误:“换行”是该功能 – dpalm

+0

一个无效的关键字参数这是Python 2.x和3.x之间的区别,请参阅编辑#1 – warownia1

1

这是完全可行的!以下是一些文档的链接: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? 

我认为应该工作。

1

你可以在你的代码的开头打开该文件,然后只打印行后添加写语句。事情是这样的:

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 
+0

这似乎不工作?不确定应该定义的文件名是什么? – dpalm

+0

这里的文件名是一个变量(字符串),你应该把它传递给你想打开的文件的名字,比如“file.csv” –

0

最简单的方法是将标准输出重定向到一个文件:

for i in range(10): 
    print str(i) + "," + str(i*2) 

将输出:

0,0 
1,2 
2,4 
3,6 
4,8 
5,10 
6,12 
7,14 
8,16 
9,18 

,如果你运行它python myprog.py > myout.txt结果去myout中.TXT