Python 全攻略第五章 I/O with Files in Python

Python 全攻略第五章 I/O with Files in Python

課程前言

  • Store game configuration, reflect status change
  • Record the score & ranking data … etc.
  • System change logging for review or debugging

課程歸納

  • Some common methods

    • file = open(filename) → returns a file object (Best practice → combine with statement)
    • file.read() → returns a string
    • file.seek(offset, whence) → Set the location for reading
    • file.tell() → find the location
    • file.readline() → read a line → from the location of the seek
    • file.readlines() → returns a list (each line becomes an element of the list)
    • file.close() → Open a file without using with statement → need to manually close it
  • Some common file open modes

    • ‘r’ - reading mode. The default. Read the file only (the file must exist)
    • ‘w’ - writing mode. Overwrite the content (create a new file if it does not exist)
    • ‘a’ - append mode. Write data to the end of the file (the file must exist)
    • ‘r+’ - reading mode plus writing mode at the same time.
    • ‘w+’ - The exact same as r+ but → create a new file if it does not exist
    • ‘a+’ - appending and reading mode → create a new file if the file does not exist
  • Python 3 added new modes (prevent from accidentally truncate or overwrite an existing file)

    • ‘x’ - writing mode (raise FileExistsError if the file already exists)
    • ‘x+’ - reading and writing mode. (raise FileExistsError or create a new file)
  • Best Practices

    • Use the with keyword to ensure the file handle is closed once the actions completed
    • More commonly, the readlines() method is used to store an iterable collection of the file’s lines
    • Using the for loop iterator and readline() together is considered bad practice

補充資訊

  • Many free programming notes for professionals Goalkicker
# files/read_write.py
with open("a.txt", encoding="utf-8") as f, open("a_copy.txt", "x", encoding="utf-8") as fw:
 lines = [line.strip() for line in f]
 fw.write("\n".join(lines))
import shutil
shutil.copyfile("a.txt", "a_copy2.txt")
'a_copy2.txt'

81 Introduction to I/O with Files (Text file)

file = open("myfile.txt")
# print(file)
print(file.read(7)) # 讀前五個 bytes
print(" -> " * 10, "讀前七個 bytes, seek 值為 7")
print(file.read()) # 讀取整份文件, 讀取後 seek 將停在最後面,
print(" -> " * 10, "由 seek 7 往後讀整份文件至最後")
print(file.read()) # 再執行一次就讀不到東西
print(" -> " * 10, "因 seek 值已到最後,再執行一次就讀不到東西")
file.seek(0) # 移到檔案最前面
print(file.read())
print(" -> " * 10, "將 seek 歸零,再重讀一次整份文件")
file.close()
Now and
 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  讀前七個 bytes, seek 值為 7
 then
Your name comes up in conversation with my friends
 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  由 seek 7 往後讀整份文件至最後

 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  因 seek 值已到最後,再執行一次就讀不到東西
Now and then
Your name comes up in conversation with my friends
 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  將 seek 歸零,再重讀一次整份文件

82 Readline, readlines & close

file = open("myfile.txt")
# print(file.readlines()) -> returns a list
for line in file.readlines():
    print(line)
file.close()
Now and then

Your name comes up in conversation with my friends
# 當文件非常大時,不適合使用 readlines()
file = open("myfile.txt")
print(file.readline()) #讀第一行
print(file.readline()) #讀第二行
file.close()
Now and then

Your name comes up in conversation with my friends
# 套用迴圈,逐行讀取
file = open("myfile.txt")
while True:
    line = file.readline()
    if line == "":
        break
    else:
        print(line)
file.close()
Now and then

Your name comes up in conversation with my friends

83 Encoding 編碼

# 讀取含有中文的文件
file = open("myfilecht.txt", encoding="utf-8")

print(file.read(5))  # 讀前五個 bytes
print(" -> " * 10, "讀前五個字元, seek 值為 5")
print(file.read())  # 讀取整份文件, 讀取後 seek 將停在最後面,
print(" -> " * 10, "由 seek 5 往後讀整份文件至最後")
print(file.read())  # 再執行一次就讀不到東西
print(" -> " * 10, "因 seek 值已到最後,再執行一次就讀不到東西")
file.seek(0)  # 移到檔案最前面
print(file.read())
print(" -> " * 10, "將 seek 歸零後,再重讀一次整份文件")
file.close()
連結SQL
 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  讀前五個字元, seek 值為 5
資料庫、處理Excel和csv,寄送email,
一步步實作成為Python達人!
 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  由 seek 5 往後讀整份文件至最後

 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  因 seek 值已到最後,再執行一次就讀不到東西
連結SQL資料庫、處理Excel和csv,寄送email,
一步步實作成為Python達人!
 ->  ->  ->  ->  ->  ->  ->  ->  ->  ->  將 seek 歸零後,再重讀一次整份文件

84 With Statement and Modes

with open("myfile.txt") as myFile:
    fileContent = myFile.read()
    print(fileContent)
Now and then
Your name comes up in conversation with my friends
# mode a -> append (加入兩行變成四行)
with open("myfile.txt", mode="a") as myFile:
    myFile.write("Learning Python is so fun.\nLearning Java is so fun as well.\n")
# mode w -> write (直接覆蓋四行,只剩二行)
with open("myfile.txt", mode="w") as myFile:
    myFile.write(
        "Learning Python is so fun.\nLearning Java is so fun as well.\n")
# mode x -> create ( Python 3 才有, 防止覆寫並可建立新檔案)
with open("myfile1.txt", mode="x") as myFile:
    myFile.write(
        "Learning Python is so fun.\nLearning Java is so fun as well.\n")

85 Deleting Files and Folders

  • import OS module
  • os.rmdir - Can use to delete empty folder only, we can use shutil instead
import os
os.remove("index.html") # os unlink functionality
os.rmdir("newFolder")

---------------------------------------------------------------------------

OSError                                   Traceback (most recent call last)

c:\Users\joe.hu\Desktop\PyCode\Chapter05\IO in Python_81-85.ipynb Cell 16 line 3
      <a href='vscode-notebook-cell:/c%3A/Users/joe.hu/Desktop/PyCode/Chapter05/IO%20in%20Python_81-85.ipynb#X23sZmlsZQ%3D%3D?line=0'>1</a> import os
      <a href='vscode-notebook-cell:/c%3A/Users/joe.hu/Desktop/PyCode/Chapter05/IO%20in%20Python_81-85.ipynb#X23sZmlsZQ%3D%3D?line=1'>2</a> os.remove("index.html") # os unlink functionality
----> <a href='vscode-notebook-cell:/c%3A/Users/joe.hu/Desktop/PyCode/Chapter05/IO%20in%20Python_81-85.ipynb#X23sZmlsZQ%3D%3D?line=2'>3</a> os.rmdir("newFolder")


OSError: [WinError 145] The directory is not empty: 'newFolder'