python 文件的打開與讀取


其實網上其他人寫的都挺好的,我也是看他們的。辦公室用的2.7。筆記本用的3.6.發現沒有file 類,尷尬了

with  open(r'C:\Users\HBX\Documents\新建文件夾\baixi.txt' , 'r') as f:
    print (f.read())

    f.close()
    if f.close()==1:
        print ('sucess')
    else:
        print ('filue')

 python 3 沒有file 類,都是用open,沒有就創建,有就打開。寫入文件就是以" W",方式打開。看的是廖雪峰的。他的太多了。不需要啊,這個簡明python教程

有些落后,不過簡潔,確實可以。

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')

 

 

 

別人寫的博客,我復制一下。方便自己查看

 http://blog.csdn.net/u011389474/article/details/60139962

# 1.將A文件復制到B文件中去(保持原來格式)
def copy_file (inputFile, outputFile, encoding):
    fin = open(inputFile, 'r', encoding=encoding) #以讀的方式打開文件
    fout = open(outputFile, 'w', encoding=encoding) #以寫得方式打開文件
    for eachLiine in fin.readlines(): #讀取文件的每一行
        line = eachLiine.strip() #去除每行的首位空格
        fout.write(line + '\n')
    fin.close()
    fout.close()

# 2. 讀取文件中的內容,返回List列表 (加載本地詞典庫)
def read_file_list(inputFile, encoding):
    results = []
    fin = open(inputFile, 'r', encoding=encoding)
    for eachLiine in fin.readlines():
        line = eachLiine.strip().replace('\ufeff', '')
        results.append(line)
    fin.close()
    return results

# 3.讀取文件,返回文件內容
def read_file(path):
    with open(path, 'r+', encoding='UTF-8') as f:
        str = f.read()
    return str.strip().replace('\ufeff', '')

def func():
    pass


if __name__ == '__main__':
    copy_file('../data/test1.txt', '../data/text.txt','UTF-8')
    contents = read_file_list('../dict/time.dict','UTF-8')
    print(contents)

 

還有一個對文件操作的博客_http://www.jb51.net/article/87398.html

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM