Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将打印语句保存到新文件_Python_Writing - Fatal编程技术网

Python 将打印语句保存到新文件

Python 将打印语句保存到新文件,python,writing,Python,Writing,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.2700

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文件。(层/1、层/2等不需要停留)。这可行吗?如果不是,至少print语句可以生成一个与KAP文件同名的新文本文件吗

您可以使用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
可以轻松地从输入文件中读取记录。

编辑#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(','))

这是完全可行的!以下是一些文档的链接:#用于编写/阅读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

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

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

它的可能副本非常不同,请完整阅读我的问题这似乎不起作用?不确定应该定义什么文件名?这里的文件名是一个变量(字符串),您只需将要打开的文件名传递给它,例如“file.csv”TypeError:“newline”是此函数的无效关键字参数。这是python 2.x和3.x之间的区别,请参见编辑#1