1. 程式人生 > >python筆記-----文件操作

python筆記-----文件操作

創建 adl sss 2個 imp lang table 1.4 --

文件操作

創建一個文件名字為filename

內容是

BJ
SH
GD
TW

打印文件編碼

f = open("filename",‘r‘,encoding="utf-8")
print(f.encoding)

utf-8

打印在內存的編號

print(f.fileno())


3

1.文件讀操作

1.1 open()方法,模式默認讀

f = open("filename",encoding="utf-8")
data = f.read()
  print(data)

BJ
SH
GD
TW

1.2 讀前幾行

f = open("filename",encoding="utf-8")

for i in range(2):
  print(f.readline().strip())

BJ
SH

1.3 一行行讀完

f = open("filename",encoding="utf-8")
for i in f:
  print(i.strip())

BJ
SH
GD
TW

1.4 高效讀到第x行

count = 0
f = open("filename",encoding="utf-8")
for i in f:
  if count == 3:
    print(‘----------------‘)
    count += 1

  print(i.strip())
  count += 1

BJ
SH
GD
----------------
TW
ssssss

2.文件寫操作

2.1 w寫模式,如果沒有此文件就創建

f = open("filename2",‘w‘,encoding="utf-8")
f.write("wwwww")
f.close()
f1 = open("filename2",encoding="utf-8")
data = f1.read()
print(data)
f.close()

wwwww

2.2 a追加模式

在文件尾部追加

f = open("filename",‘a‘,encoding="utf-8")

f.write("\nssssss")
f.close()

BJ
SH
GD
TW
ssssss

2.3讀+追加模式

f = open("filename","r+",encoding="utf-8")
f.write("\n------haha------------")

for i in f:
  print(i.strip())

2.4 文件修改

f = open("filename","r",encoding="utf-8")
f1 = open("filename1","w",encoding="utf-8")

for line in f:
  if "h" in line:
    line = line.replace(‘h‘,‘g‘)
  f1.write(line)
f.close()
f1.close()

3.指針操作

f = open("filename",encoding="utf-8")
print(f.tell()) #查看當前指針位置
print(f.readline())
print(f.tell())
f.seek(0) #指針回到0
print(f.tell())
print(f.readline())
print(f.tell())

0
BJ

4
0
BJ

4

4.判斷文件是否可讀可移可寫

f = open("filename",‘r‘,encoding="utf-8")

print(f.readable())
print(f.seekable())
print(f.writable())

True
True
False

5.flush方法和buffer方法

f = open("filename",‘r‘,encoding="utf-8")
print(f.flush())#從內存寫入磁盤
print(f.buffer)

None
<_io.BufferedReader name=‘filename‘>

6.實現進度條

import sys,time

for i in range(10):
  sys.stdout.write("#")
  sys.stdout.flush()
  time.sleep(0.5)

##########

7.截斷

f = open("filename","a",encoding="utf-8")
f.seek(0) #指定指針到0的位置

f.write("123456")

f.truncate(2) #截斷2字符

filename文件中 只保留2個字符

BJ

python筆記-----文件操作