Ch5 I/O with Files in Python
✨與文件同一個資料夾叫出
For txt
- file = open(filename) #opens a file and returns as a file object
- file.read() #return the specified number of bytes from the file 全篇輸出 ‘string’
- file.readline() #return a line of text of our current position 輸出 ‘list’(a list of strings)
- file.readlines #return a list of containing each line in the file as a list item 全篇輸出 ‘list’(a list of strings)
增加佔據RAM
- file.seek(offest) #set the file’s current position at the offset 讀取處從指定處開始 (0)指向起點
- file.close() #不執行不會怎樣,但打開太多檔案會佔據太多RAM => 不論檔案大小,最好都要close
file = open('myfile.txt')
print(file)
#<_io.TextIOWrapper name='myfile.txt' mode='r' encoding='cp1252'>
print(file.read()) #輸出所有內容
file.seek(0)
print(file.read(5)) #seek 會變
print(file.read(5)) #接續前面讀取的地方
print(file.readlines()) #接續前面讀取的地方
for line in file.readlines():
print(line)
while True:
line = file.readline()
if line == '': #也可以打 if not line => 如果沒有讀到東西
break
else:
print(line)
(Bonus) Encoding
- character encoding is the process of assigning numbers to graphical characters ⇒ a = 20
- common encoding: utf-8 (html常用), cp950(中日文電腦), ASCII
- open() based on default, Chinese Windows ⇒ cp950
if want to open utf-8 file, must type:
open(filename, encoding = ‘utf-8’)
With Statement and Open() Function
- cleaner and readable, also will automatically close the file
- 設定開啟模式:
- r : read (default) #open file for reading, error if file doesn’t exist
- a : append #open for appending, create the file if it doesn’t exist #文件變得unreadable, 不能用read()
- w : write #open for writing, create the file if it doesn’t exist
- x : create #return an error if file exists
with open('myfile.txt', mode = 'r') as myfile:
all_content = myfile.read()
print(all_content)
with open('myfile.txt', mode = 'a') as myfile:
myfile.write('Hi! It is a great day')
#新增行
with open('myfile.txt', mode = 'w') as myfile:
myfile.write('Hi! It is a great day.\\n Want to go out?')
#覆蓋、複寫行(文件中只剩這一行)
Deleting Files and Folders