【问题标题】:Output for a nested 'while' loop function in Python into a text file将 Python 中嵌套的“while”循环函数输出到文本文件中
【发布时间】:2013-01-21 21:25:53
【问题描述】:

我一直在尝试将 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))

【问题讨论】:

  • 使用format() 没有任何格式规范是没用的,改用str() 或者更好地进行字符串格式化。

标签: python loops while-loop nested text-files


【解决方案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()

【讨论】:

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

这会将stdout 上的输出打印到文件中。您是否在 write() 函数中使用了“,”?它将它视为两个单独的参数。

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

写(...)
写(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))

【讨论】:

    【解决方案3】:
    #! /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) )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多