精英盒子 -> 程序设计 -> 闲的实在没事干,写了个小Python程序 [打印本页]

编程土豆 2012-07-14 17:49

闲的实在没事干,写了个小Python程序

  1. import os
    ls = os.linesep

    i = input("Enter '1' to read;Enter '2' to make a file;Enter '3' to edit a file:")

    if i == 1:
        'readTextFile.py -- read and display text file'

        # get filename
        fname = raw_input('Enter file name: ')
        print

        # attempt to open file for reading
        try:
            fobj = open(fname, 'r')
        except IOError, e:
            print"*** file open error:", e
        else:
            # display contents to the screen
            for eachLine in fobj:
                print eachLine,
            fobj.close()
    elif i == 2:
        #获取文件名
        while True:
            try:
                fname = raw_input("Please Enter File Name:")
            except IOError, e:
                print "*** file open error:", e
            else:
                break

        all = []
        print "\nEnter lines ('.' by itself to quit).\n"

        while True:
            entry = raw_input('>')
            if entry == '.':
                break
            else:
                all.append(entry)

        #输入到文件
        fobj = open(fname, 'w')
        fobj.writelines(['%s%s' % (x, ls) for x in all])
        fobj.close()
        print "DONE"


whtsky 2012-07-14 19:09
不要用input.
另外,不知道你为什么要捕获异常。

whtsky 2012-07-14 19:15
input是执行所得的输入结果。
你可以试试在提示Enter '1' to read;Enter '2' to make a file;Enter '3' to edit a file:的时候输入:__import__("sys").exit()

whtsky 2012-07-14 19:19
 1 import os
 2 
 3 i = int(raw_input("Enter '1' to read;Enter '2' to make a file;Enter '3' to edit a file:"))
 4 
 5 if i == 1:
 6     �| �| �| �| 'readTextFile.py -- read and display text file'
 7 
 8 �| �| �| �| # get filename
 9 �| �| �| �| fname = raw_input('Enter file name: ')
10 �| �| �| �| print
11 
12 �| �| �| �| # attempt to open file for reading
13     print open(fname, 'r').read()
14 
15 elif i == 2:
16     �| �| �| �| #�~N��~O~V�~V~G件�~P~M
17 �| �| �| �| fname = raw_input("Please Enter File Name:")
18 �| �| �| �| fobj = open(fname, 'w')
19 
20 �| �| �| �| print "\nEnter lines ('.' by itself to quit).\n"
21 
22 �| �| �| �| while True:
23     �| �| �| �| �| �| �| �| entry = raw_input('>')
24 �| �| �| �| �| �| �| �| if entry == '.':
25     �| �| �| �| �| �| �| �| �| �| �| �| fobj.close()
26 �| �| �| �| �| �| �| �| else:
27     �| �| �| �| �| �| �| �| �| �| �| �| fobj.write(entry)
28             fobj.write(os.linesep)
29 
30 �| �| �| �| print "DONE"

whtsky 2012-07-14 19:20
擦,colorit也那么不靠谱了//

jybox 2012-07-14 22:30




Powered by phpwind v8.7 Code ©2003-2011 phpwind
Time 0.057060 second(s),query:5 Gzip enabled