2013-01-21 40 views
0

我一直试图将Python中嵌套'while'循环函数的输出转换为文本文件。我知道“写入文件”是:将Python中的嵌套'while'循环函数输出到文本文件中

TheFile=open("C:/test.txt","w") 
TheFile.write("Hello") 
TheFile.close() 

但希望得到我的纬度和经度的嵌套循环的输出,当我应该使用坐标转换成文本文件?我能得到我想要的东西从打印功能,但不能似乎得到它到一个文本文件...感谢:

lat=-100 
long=-190 
while lat <=80: 
    lat=lat+10 
    long=-190 
    while long<=170: 
     long=long+10 
    print ("latitude:"+format(lat),"longitude:"+format(long)) 
+0

使用'格式()'无任何格式规范是没用的,使用'STR()'代替或更好的去为字符串格式化。 –

回答

1

仅使用一个TheFile=open("C:/test.txt","w")语句,只有一个TheFile.close()声明,并确保他们在所有循环之外。

然后,您可以使用file=参数到print,否则将它保持为完全相同的print语句。

在你的榜样,是这样的:

TheFile=open("C:/test.txt","w") 
lat=-100 
long=-190 
while lat <=80: 
    lat=lat+10 
    long=-190 
    while long<=170: 
     long=long+10 
     print ("latitude:"+format(lat),"longitude:"+format(long), file=TheFile) 
TheFile.close() 
+0

请注意'file = TheFile'在py2x中不起作用。 –

+0

@AshwiniChaudhary:我的假设是OP使用Python 3.0,因为他使用了括号。当然,这在2.x中也是有效的语法,这只是没有必要的。 –

1

这将打印印上stdout到文件的输出。你在write()函数中使用了','吗?它将其视为两个独立的论点。

更多关于来自Python shell的帮助的write

写(...)
写(STR) - >无。将字符串str写入文件。

Note that due to buffering, flush() or close() may be needed before 
the file on disk reflects the data written. 

试试这个代码:

with open("output","w") as f: 
    lat=-100 
    long=-190 
    while lat <=80: 
    lat=lat+10 
    long=-190 
    while long<=170: 
     long=long+10 
     f.write("latitude:"+format(lat)+" longitude:"+format(long)) 
+0

使用'with'语句+1。 –

1
#! /usr/bin/python3.2 

with open("out2.txt","w") as f: 
    for lat in range (-90, 100, 10): 
     for lon in range (-180, 190, 10): 
       f.write ("latitude: {}\tlongitude: {}\n".format (lat, lon))