# Python檔案讀寫 ###### tags: `基本語法` ## with open as 語句 在Python中,可以使用`with open("file_path","open_mode") as varialbe`語句讀/寫基本檔案。 其中有以下常見的檔案開啟模式: | 模式 |功能|特性| | -------- | -------- | -------- | |"w"|只能寫入|指標位於檔頭| |"r"|只能讀取|指標位於檔頭| |"a"|只能寫入(填加)|指標位於檔位| ## 基本的寫入語法 1. `.write(str)` 將字串寫入。 2. `.writelines()` 將如可迭代的字串資料寫入。 程式範例 ```python! with open('1.txt', 'w') as file: text = "hello world\n" texts = ["how ", "are ", "you?"] file.write(text) file.writelines(texts) ``` 1.txt ``` hello world how are you? ``` ## 基本的讀取語法 1. `.read(int|None)` 返回讀取的字串,如果沒有傳入參數就讀取整個檔案,否則則讀取指定的字元數。 2. `.readline()` 讀取第一行 3. `.readlines()`讀取所有行數,回傳成一個串列 ### `read()`程式範列 ``` 1.txt hello world how are you? ``` ```python! with open('1.txt') as file: all_content = file.read() print(all_content) ``` ``` output: hello world how are you? ``` ### `readline()`程式範列 ```python! with open('1.txt') as file: line = file.readline() print(line) ``` ``` output: hello world ``` ### `readlines()`程式範列 ```python! with open('1.txt') as file: lines = file.readlines() print(lines) ``` ``` output: ['helloworld\n', 'how are you?'] ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up