file = open('myFile.txt') #取得一個file物件
print(file.read())
file.seek(0)
print(file.read(5))
print(file.read(5))
print(file.read(5))
print(file.readline())
print(file.readline())
file.close()
-----------------------------------
hello, how are you today?
I'm fine, thank you.
hello
, how
are
you today?
I'm fine, thank you.
file = open('myFile.txt')
while True:
line = file.readline()
if not line: # if line is empty dtring then end to read
break
else:
print(line)
file.close()
在繁中windows系統中預設編碼是cp950(big 5),則如果要打開一個utf-8的文件則要使用encoding的參數
file = open('myFile.txt', encoding='utf-8')
可讀性較高的寫法且會幫我們自動close
with open('myFile.txt') as my_file:
all_content = my_file.read()
print(all_content)
---------------------------------
hello, how are you today?
I'm fine, thank you.
with open('myFile.txt') as my_file:
all_content = my_file.read().splitlines()
for i in range(len(all_content)):
print(all_content[i])
---------------------------------
hello, how are you today?
I'm fine, thank you.
with open('myFile.txt') as my_file:
for line in my_file.readlines():
print(line)
---------------------------------
hello, how are you today?
I'm fine, thank you.
with open('myFile.txt') as my_file:
doc = my_file.readlines()
doc = ''.join(doc).strip('\\n')
---------------------------------
hello, how are you today?
I'm fine, thank you.