Python 中的文件读写

# 文件的读写

open(name,mode,flush)

name: 文件的路径

mode: 打开的模式

flush: 缓冲,1 代表有缓冲,0 代表无缓冲

f = open('D:doujiao.txt','r',0)

## 如何读取文件

### 打开文件

1.注意路径的写法

open('D:/doujiao.txt','r')

open('D:\doujiao.txt')

open(u'D:/豆角.txt')

注:python 中 "" 是转译字符,所以在写路径的时候避免用 ""

2.文件打开的模式如果不写,默认是只读模式 "r"

### 读取文件

read( ): 读取全部

r = f.read()
print r

readline( ): 逐行读取

r = f.readline()
while r:
    print r

readlines( ): 读取所有行到一个列表(list)

r = f.readlines()
print r
for line in r:
    print line

with: 用 with 做某个操作,操作完成后,with会自动处理关闭的操作

with open('D:/doujiao.txt','r') as f:
    r = f.readlines()
    print r

## 如何向文件中写入内容

1.打开文件

2.打开文件的模式

  详见下表

3.写的方法

write( ) # 往文件里写一串字符

writelines( ) # 往文件里写一个字符或一个序列

注:如果写入时是用 'wb' 'wb+' 'rb+' ,那么读取的时候最好用 'rb' 'rb+' ,否则可能出现读取不全的现象

原文地址:https://www.cnblogs.com/luffy-py/p/6524883.html