第十天学习:file文件用法

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()
读取整行,包括 " " 字符
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!
shenzhen
')
print(file.tell())
file.writelines(['aaaa
', 'bbbb
', 'cccc
', 'dddd
'])
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:Python27python.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,)

  

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