码迷,mamicode.com
首页 > 其他好文 > 详细

第十天学习:file文件用法

时间:2017-10-28 11:16:48      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:pyc   返回值   覆盖   adl   数据   code   方法   bsp   读文件   

1、读文件

(1).open文件
(2).写入或读取文件
(3).关闭close文件
import codecs

f = codecs.open(‘1.txt‘)
text = f.read()
result = text.replace(‘today‘, ‘tomorrow‘)
print(result)
f.close()

  

2、写文件

import codecs

f = codecs.open(‘1.txt‘, ‘w‘)
f.write(‘today is sunday‘)

f.close()

#codecs 用来解决文件乱码的问题
#open(filename, mode)

  

r 只能读 
r+ 可读可写 不会创建不存在的文件 从顶部开始写 会覆盖之前此位置的内容 
w+ 可读可写 如果文件存在 则覆盖整个文件不存在则创建 
w 只能写 覆盖整个文件 不存在则创建 
a 只能写 从文件底部添加内容 不存在则创建 
a+ 可读可写 从文件顶部读取内容 从文件底部添加内容 不存在则创建
 
 
3、常用方法
 
file.readlines()
读取所有行并返回列表
file.readline()
读取整行,包括 "\n" 字符
file.write()
将字符串写入文件,没有返回值
file.writelines()
向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符
 
file.flush()
刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。
file.seek()
设置文件当前位置
file.tell()
返回文件当前位置。
import codecs

file = codecs.open(‘3_2.txt‘, ‘wb‘)
print(dir(file))
file.write(‘hello world!\nshenzhen\n‘)
print(file.tell())
file.writelines([‘aaaa\n‘, ‘bbbb\n‘, ‘cccc\n‘, ‘dddd\n‘])
print(file.tell())
file.flush()
file.seek(0)
file.write(‘this is theather is so very cool‘)
file.close()

  

4、with用法

with open(‘1.txt‘) as fd:
    print(fd.read())
    print(fd.closed)
print(fd.closed)

D:\Python27\python.exe D:/PycharmProjects/learn5/5.1.py
today is sunday
False
True

Process finished with exit code 0 

with open(‘3_2.txt‘) as fd:
    for i, line in enumerate(fd):
        print(i, line,)

  

第十天学习:file文件用法

标签:pyc   返回值   覆盖   adl   数据   code   方法   bsp   读文件   

原文地址:http://www.cnblogs.com/yshan13/p/7745844.html

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