博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 文件操作
阅读量:4627 次
发布时间:2019-06-09

本文共 1681 字,大约阅读时间需要 5 分钟。

f=open('test.txt','w',encoding='utf8')f.write('hello\n')f.close()f=open('test.txt','a')f.write('2hello')f.close()f=open('test.txt','r')print(f.read(1))print(f.readline())#读到回车,再加上print的回车,一共两个回车print(f.read())#由于读光标的原因,它不会重头再readf.close()
hello2hello
f=open('test.txt','r',encoding='utf-8')for i in f.readlines():#f.readlines一行一行读取的集合    print(i.strip())#去掉每行的回车,否则会与print自带的回车重复,换两行f.close()

 以上方法不常用

 

f=open('1.txt','r',encoding='utf8')for i in f:    print(i.strip())  #常用f.close()

 

f=open('1.txt','r',encoding='utf8')print(f.tell())#找光标的位置print(f.read(2))#一个中文占三个字符,光标的位置走6print(f.tell())f.seek(3)#将光标移到第一个中文后,写不是3的倍数读取中文时会报错print(f.read(3))f.close()
0君不6不见,

 报错:

 flush的作用:

import sys,time#下面会一次性出现30个*,因为是写在缓冲区的,写好后一次性显示出来for i in range(30):    sys.stdout.write("*")    time.sleep(0.2)#下面类似进度条的效果,因为flush能将缓冲区的东西马上显示出来for i in range(30):    sys.stdout.write("*")    sys.stdout.flush()    time.sleep(0.2)
#以上sys.stdout可以使用print('*',end='',flush='True')替换

 truncate截断方法:

f=open('1.txt','w',encoding='utf8')f.write('helloworld')f.truncate(5)#只保留前5个,截断,文件中显示hellof.close()

 文件模式:

r+:读写模式,读正常,写的时候在最后写,但写了之后光标移动到最后,想要再读需要移动光标

w+:写读模式,写在最开始写,会覆盖原来的内容,想要读的时候要移动光标,基本上不用

a+:光标一开始在最后,读写都是在最后,不会覆盖

文件拷贝以及修改:

number=0f1=open('1.txt','r',encoding='utf8')f2=open('2.txt','w',encoding='utf8')for line in f1:    number+=1    if number==2:        f2.write(''.join([line.strip(),' I like this sentence\n']))    else:        f2.write(line)f1.close()f2.close()

 以下代码能实现同样功能:(用 with 同时管理多个文件对象,with a as b 相当于 b=a)

with open('1.txt','r',encoding='utf8') as f1,open('2.txt','w',encoding='utf8')as f2:    for line in f1.readlines():        f2.write(line)

 

转载于:https://www.cnblogs.com/pqhuang/p/11270494.html

你可能感兴趣的文章
POJ-1185 炮兵阵地 动态规划+状态压缩
查看>>
NYOJ 366 D的小L
查看>>
PYTHON 写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者...
查看>>
Docker 初识
查看>>
【12.16】VC++调用Word OLE进行自动化生成报表
查看>>
用Maven创建第一个web项目
查看>>
php中的抽象类(abstract class)和接口(interface)
查看>>
linux安装ActiveMQ
查看>>
面向对象与软件工程---团队作业1
查看>>
认识一下Kotlin语言,Android平台的Swift
查看>>
hdu5389 Zero Escape
查看>>
【转】android电池(四):电池 电量计(MAX17040)驱动分析篇
查看>>
week6
查看>>
android中的回调
查看>>
redis启动、清缓存命令
查看>>
Java的Clone
查看>>
CSS 弹出层 支持IE/FF/OP
查看>>
maven的配置-2019-4-13
查看>>
进程调度
查看>>
百练 2973 Skew数 解题报告
查看>>