Ch5 I/O with Files in Python

✨與文件同一個資料夾叫出

For txt

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

With Statement and Open() Function

  1. r : read (default) #open file for reading, error if file doesn’t exist
  2. a : append #open for appending, create the file if it doesn’t exist #文件變得unreadable, 不能用read()
  3. w : write #open for writing, create the file if it doesn’t exist
  4. 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