【问题标题】:Saving print statement to new file将打印语句保存到新文件
【发布时间】:2016-08-08 15:00:22
【问题描述】:

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 文件同名的新文本文件吗?

【问题讨论】:

标签: python writing


【解决方案1】:

这是完全可行的!以下是一些文档的链接:https://docs.python.org/2/library/csv.html#for writing/reading CSV。 您也可以使用常规文件读取/写入功能制作自己的 CSV。

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

我认为这应该可行。

【讨论】:

    【解决方案2】:

    您可以在代码的开头打开文件,然后在打印行之后添加一个 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
    

    【讨论】:

    • 这似乎不起作用?不确定应该定义什么文件名?
    • filename 这里是一个变量(字符串),你应该把你要打开的文件的名字传给它,比如“file.csv”
    【解决方案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

    编辑#1

    在 python 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(','))
    

    【讨论】:

    • TypeError: 'newline' is an invalid keyword argument for this function
    • 这是python 2.x和3.x的区别,见编辑#1
    【解决方案4】:

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

    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

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2020-10-03
      • 2018-07-03
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2014-06-06
      相关资源
      最近更新 更多