F****3 发帖数: 1504 | 1 问题很白,真是不好意思。
What I want to do is to read the input.txt file line by line and then put
into a function and write the output line by line to output.txt.
with open('/path/to/directory/input.txt','r') as f:
with open('/path/to/directory/output.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
print >> g, some_lib.some_function(x)
But sometimes the function won't be able to generate the output for x, and
report error. I tried to use exception handling in Python, but the program
loops over the first line instead of moving on to the next line.
with open('/path/to/directory/input.txt','r') as f:
with open('/path/to/directory/GeoIP/output.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
while True:
try:
print >> g, some_lib.some_function(x)
except ValueError:
print >> g, "cannot find value"
请问我哪里搞错了?不好意思我是文科的。。。 | w****k 发帖数: 6244 | 2 while true caused infinite loop
why do u need that line?
【在 F****3 的大作中提到】 : 问题很白,真是不好意思。 : What I want to do is to read the input.txt file line by line and then put : into a function and write the output line by line to output.txt. : with open('/path/to/directory/input.txt','r') as f: : with open('/path/to/directory/output.txt','w') as g: : for x in f: : x = x.rstrip() : if not x: continue : print >> g, some_lib.some_function(x) : But sometimes the function won't be able to generate the output for x, and
| F****3 发帖数: 1504 | 3 太谢谢了!
我把while true干掉以后就可以了。
但是出现exception的时候好像程序直接跳过print >> g, "cannot find value",没有
写入错误信息怎么办?
with open('/path/to/directory/input.txt','r') as f:
with open('/path/to/directory/GeoIP/output.txt','w') as g:
for x in f:
x = x.rstrip()
if not x: continue
try:
print >> g, some_lib.some_function(x)
except ValueError:
print >> g, "cannot find value"
结果就是我有100个input,output文件只有50几个。。。,我希望output也有一百个,
只是有些是“cannot find value” | i***r 发帖数: 1035 | 4 你确定exception 是 value error么?
【在 F****3 的大作中提到】 : 太谢谢了! : 我把while true干掉以后就可以了。 : 但是出现exception的时候好像程序直接跳过print >> g, "cannot find value",没有 : 写入错误信息怎么办? : with open('/path/to/directory/input.txt','r') as f: : with open('/path/to/directory/GeoIP/output.txt','w') as g: : for x in f: : x = x.rstrip() : if not x: continue : try:
| F****3 发帖数: 1504 | 5 报错是这样的:
File "GeoIPcity.py", line 10, in
print >> g, gi.cityby_name(x)
File "build/bdist.linux-i686/egg/pygeoip/__init__.py", line 551, in org_by
_name
File "build/bdist.linux-i686/egg/pygeoip/__init__.py", line 412, in _
gethostbyname
socket.gaierror: [Errno -5] No address associated with hostname
这个是不是ValueError啊?其他的我不知道了。。。请问还有可能是什么种类的
exception我可以一个一个套。用的是geoip的包。
太谢谢了! |
|