码迷,mamicode.com
首页 > 编程语言 > 详细

python 文件的打开与读取

时间:2018-02-01 21:13:08      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:读取   blog   ace   __name__   adl   pre   ret   空格   res   

其实网上其他人写的都挺好的,我也是看他们的。办公室用的2.7。笔记本用的3.6.发现没有file 类,尴尬了

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

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

 

别人写的博客,我复制一下。方便自己查看

 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)

 

python 文件的打开与读取

标签:读取   blog   ace   __name__   adl   pre   ret   空格   res   

原文地址:https://www.cnblogs.com/sakura3/p/8401240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!