文件

f=open('ly.txt','r',encoding='utf-8') # 文件句柄 'w'为创建文件,之前的数据就没了
data=f.read()
print(data)
f.close()
f=open('test','a',encoding='utf-8') # 文件句柄 'a'为追加文件 append
f.write("\n阿斯达所,\n天安门上太阳升")
f.close()
f = open('ly.txt', 'r', encoding='utf-8')  # 文件句柄
for i in range(5):
    print(f.readline().strip())  # strip()去掉空格和回车


for line in f.readlines():
    print(line.strip())

# 到第十行不打印

for index,line in enumerate(f.readlines()):
    if index==9:
        print('----我是分隔符-----')
        continue
    print(line.strip())
# 到第十行不打印
count=0
for line in f:

    if count==9:
        print('----我是分隔符-----')
        count += 1
        continue
    print(line.strip())
    count += 1
f = open('ly.txt', 'r', encoding='utf-8')  # 文件句柄
print(f.tell())
print(f.readline(5))
print(f.tell())
f.seek(0)
print(f.readline(5))
print(f.encoding)
print(f.buffer)
print(f.fileno())
print(f.flush()) # 刷新缓冲区
# 进度条
import sys,time
for i in range(50):
    sys.stdout.write('#')
    sys.stdout.flush()
    time.sleep(0.5)
f = open('ly.txt', 'a', encoding='utf-8')  # 文件句柄
f.seek(10)
f.truncate(20) # 指定10到20个字符,10个字符前面留着,后面20字符清除
f = open('ly.txt', 'r+', encoding='utf-8')  # 文件句柄
print(f.readline().strip())
print(f.readline().strip())
print(f.readline().strip())
f.write("我爱中华")
f.close()


# 实现简单的shell sed替换功能

f=open("ly.txt","r",encoding="utf-8")
f_new=open("ly2.txt","w",encoding="utf-8")

for line in f:
    if "肆意的快乐" in line:
        line=line.replace("肆意的快乐","肆意的happy")
    f_new.write(line)

f.close()
f_new.close()

import sys
f=open("ly.txt","r",encoding="utf-8")
f_new=open("ly2.txt","w",encoding="utf-8")
find_str = sys.argv[1]
replace_str = sys.argv[2]
for line in f:
    if find_str in line:
        line=line.replace(find_str,replace_str)
    f_new.write(line)
f.close()
f_new.close()

# with语句---为了避免打开文件后忘记关闭,可以通过管理上下文
with open('ly.txt','r',encoding='utf-8') as f:
    for line in f:
        print(line.strip())
# python2.7后,with又支持同时对多个文件的上下文进行管理,即:
with open('ly.txt','r',encoding='utf-8') as f1,open('ly2.txt','r',encoding='utf-8'):
    pass

output:
0

0

utf-8
<_io.BufferedReader name=‘ly.txt’>
4
None
##################################################

我爱中华

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值