文本文件的读写流程
1.请求操作系统开启一个文件接口对象(文件描述符)
2.通过操作系统提供的接口从文件接口对象中进行读/写操作
1.准备写入类
x = list(range(10))
print(x)
# 将列表中的每一项作为一行写入到文本文件中
2.开启文件接口对象---open
file= open('1.txt','w')
# 以写入模式开启一个文件接口对象(文本形式写入),如果该文件在指定的路径中不存在,就创建一个,如果存在,就打开该文件
# 返回一个文件接口对象
'''
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
file : 要开启的文件,如果该文件是用来进行写入,可以事先不存在,python会自动建立该文件
mode : 对文件进行的操作模式
encoding : 文件的编码,中文常用utf-8和GBK,python默认的中文编码是utf-8,windows操作系统默认的中文编码是GBK
'r' open for reading (default) # 读
'w' open for writing, truncating the file first # 写
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists # 附加
'b' binary mode # 二进制模式 用来操作非文本文件
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
'''
3.写入内容到文件
#file.write(x) # 注意:write方法是将字符串内容写入到文本文件中,如果不是字符串要转成字符串,否则会报错
1)一次性写入整个列表
file.write(str(x))#返回一个长得像列表的字符串
file.close()## 对文件的操作完成之后,记得关闭文件接口对象,释放资源,避免出错
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2)分开写入
#3.2分开写入
file1=open('1.txt','w')
for i in x:
file1.write(str(i)+'\n')
file.close()
0
1
2
3
4
5
6
7
8
9
文本文件的读取
'''
with open(file, mode, encoding) as 对象名:
对文件要进行的操作
'''
1.开启文件准备读取
with open('1.txt',mode='r',)as file1:
print(file1)
print('rean file:\n',file1.read())# 读取文件中的所有内容,返回一个字符串对象
#3.按行读取
with open('1.txt', 'r')as file2:
print('所有行', file2.readlines())
#展示前五行
for i in file2.readlines()[:4]:#file2.readlines() 是一个列表,提取前五行内容【:5】
print('每一行:',i)
#for循环没有输出结果 因为:前一个readlines()执行完之后,文件的指针已经指向文件的末尾,此时再进行文件的读取就无法读取到内容了,所以此处没有任何输出
# 解决方法2:读取完成后,通过seek方法将指针复位,把文件指针移动到文件开头位置,相当于重新打开文件
with open('1.txt','r')as file3:
file4=file3.readlines()
print(file4)
for i in file4[:4]:
print('每1行',i,end='')
# 英文文件中的每一行都带有换行符,因此要取消print中的结束标识,否则每行后面会多一行空行
print('-' * 100)
# 解决方法2:读取完成后,通过seek方法将指针复位,把文件指针移动到文件开头位置,相当于重新打开文件
with open('1.txt','r')as file4:
print(file4.read()) # 读取完成,指针指向尾部
file4.seek(0) # 复位指针到文件头位置 相当于重新打开文件
print(file4.readlines())
用文本方式写入csv文件
# Windows操作系统默认的中文编码是GBK,而pycharm默认的编码是utf-8,因此直接打开以GBK编码写入的csv文件时,会出现乱码,改为以GBK开启即可解决
# 也可以直接在写入时指定用utf-8编码进行写入
with open('2.csv','w',encoding='utf-8')as csv2:
csv2.write('id,url,namen\n')
csv2.write('1,http://www.jd.com,京东\n')
csv2.write('1,http://www.tm.com,天猫\n')
csv2.write('1,http://www.pdd.com,拼多多\n')
with open('1.csv','r')as csv3:
print(csv3.read())