python的一个程序运行出错 - Breeze's Blog

python的一个程序运行出错

Breeze posted @ 2011年3月07日 01:29 in Linux编程 , 1825 阅读

最近学习python,遇到一个程序,运行出错,不知为什么。

程序如下:

#!/usr/bin/env python

'makeTextFile.py -- create text file'

import os
ls = os.linesep

# get filename
while True:

if os.path.exists(fname):
   print "ERROR: '%s' already exists" % fname
else:
   break

# get file content (text) lines
all = []
print "\nEnter lines ('.' by itself to quit).\n"

# loop until user terminates input
while True:
   entry = raw_input('> ')
   if entry == '.':
      break
   else:
      all.append(entry)

# write lines to file with proper line-ending
fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE!'
 

运行出错如下:

  File "./makeTextFile.py", line 11
    if os.path.exists(fname):
     ^
IndentationError: expected an indented block

 

Avatar_small
Garfileo 说:
2011年3月07日 02:14

while 块之后的 if ... else 块代码的缩进不正确

Avatar_small
Garfileo 说:
2011年3月07日 02:14

在 #get filename 那里

Avatar_small
Breeze 说:
2011年3月07日 02:30

@Garfileo: 改变缩进还是不行啊,运行出错如下:
Traceback (most recent call last):
File "./makeTextFile.py", line 11, in <module>
if os.path.exists(fname):
NameError: name 'fname' is not defined

Avatar_small
Garfileo 说:
2011年3月07日 06:44

那是自然的了,fname 是你的文件名,你在开始处添加:

fname = "you-file-name"

就可以了。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee