第四章ファイルのコピー操作&
4.1ファイル操作
4.1.1ファイルを作成します。
1:
f1 =open('a.txt',mode='w',encoding='utf-8')
2:
with open('a.txt',mode='w',encoding='utf-8') as f1 :
# 自动缩进 编写文件 自己关闭文件
4.1.2オープンモード
- wの書き込みは、文書の元のコンテンツをクリアします
- R读読みます
- 書かれた最後の追加のファイル
- W + / + R / A +読み出しおよび書き込み動作
- バイナリ動作再開可能とWB / RB / AB
- W + B / R + B / A + B
4.1.3ファイルを閉じます
f1 =open('a.txt',mode='w',encoding='utf-8')
f1.close() # 每个文件打开操作后 关闭
4.1.4読み取り/書き込み/追加
Wライト・ファイル
# -------------------写,但覆盖原来文件------------------- f = open('文件',mode='w',encoding=('utf-8')) f.write('吃葡萄不吐葡萄皮,不吃葡萄倒吐葡萄皮') f.close()
Rファイルの内容を読み取ります
# --------------读 r------------------------------------ f = open('文件',mode='r',encoding=('utf-8')) s=f.read() print(s) f.close() #------也可以循环的读取文件 with open('文件','r',encoding='utf-8')as f1 : for i in f1 : print(i)
追加のファイルの最終
f= open('文件',mode='a',encoding='utf-8') f.write("\nales,大王牛逼")#\n换行 f.close()
読み取りおよび書き込み操作
W +
with open('文件',mode='r+',encoding='utf-8') as f1 : f1.write('alex sb') f1.seek(0) # 移动光标位置 不移动读的空白 s =f1.read() print(s)
R +
with open('文件',mode='r+',encoding='utf-8') as f1 : s =f1.read() f1.write('alex sb') # 因为读完后 光标在最后写入内容,不会覆盖原来的内容 print(s)
+
with open('文件',mode='a+',encoding='utf-8') as f1 : f1.write('alex sb') f1.seek(0) s =f1.read() print(s)
4.1.5ファイル操作
ファイルの修正
# 只能读取到内存再修改 ,直接在硬盘上只能对应的字节 n = open('文件','r+',encoding='utf-8') r = n.read() read =r.replace('王豪','哈哈') n.seek(0) n.write(read) n.close() import os import time #时间模块 with open('文件',mode='r',encoding='utf-8')as f1,\ open('文件_副本',mode='w',encoding='utf-8')as f2 : for line in f1 : line=line.replace('alse','sb') f2.write(line) time.sleep(3) os.remove('文件')#删除 time.sleep(3) os.rename('文件_副本','文件')#重新命名alse,大王牛逼
シーク
位置対応にカーソルを移動バイト書き込まアンに従って符号化
# 文件的内容是 ‘哈哈alex sbalex sbalex sb’ with open('文件',mode='r',encoding='utf-8') as f1 : f1.seek(7) s = f1.read(1) print(s) # l f1.seek(3) s = f1,read(1) print(s) #哈 特殊情况 a+ with open('文件',mode='a+',encoding='utf-8') as f1 : f1.seek(0) f1.write('alex sb') #光标移动到开头,但追加只在最后写 f1.seek(0) s =f1.read() print(s)
読む
あなたは、読み出したコンテンツ(文字)の数を指定することができます
# 文件的内容是 ‘哈哈alex sbalex sbalex sb’ with open('文件',mode='r',encoding='utf-8') as f1 : s = f1.read(1) print(s) # 哈
カーソルの戻り位置を伝えます
with open('文件',mode='r',encoding='utf-8') as f1 : f1.seek(7) s = f1.tell() print(s)
4.1.6 HTTP
WB / RB / AB
f1 = open('文件',mode='wb') n = '王豪傻逼,寂寞了' n = n.encode('utf-8') # 忘了 看3.3.5 f1.write(n) f1.close()