一個簡單的python讀寫文件腳本

jopen 9年前發布 | 7K 次閱讀 Python

    #!/usr/bin/env python

'makeFile.py -- create a file'  

import os  
ls = os.linesep  

# get filename  
while True:  
    fname = raw_input('Input an unused file name >')  
    if os.path.exists(fname):  
        print "ERROR: '%s' already exists" %fname  
    else:  
        break  

# get file content lines  
all = []  
print "\nEnter lines (input '.' 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'  

if __name__ == '__main__':  
    print 'innter module'  </pre> 


上面的代碼用來創建一個新文件并寫入文本,第6行給os模塊中的linesep起了給別名ls,這樣做的好處一方面簡化了長長的變量名,另一方面也是主要原因用于提高代碼性能,因為訪問這個變量時首先要檢測os模塊,然后再解析linesep,linesep是行結束符標志,linux下是'\r',windows下是'\r\n',用本地變量保存更好。第34行使用了__name__,這主要用于代碼內測試,它的值是__main__,但python文件通常作為模塊被其它文件import,這時__name__的值是這個模塊名,就不會執行模塊內的測試代碼了。

    #!/usr/bin/env python  

    'readFile.py -- read and display file'  

    # get filename  
    fname = raw_input('Enter filename >')  
    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()  

上面的代碼用來讀文件并顯示其內容到屏幕上,使用了try-except-else異常處理機制。

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!