---
# System prepended metadata

title: 檔案讀寫
tags: [課堂筆記]

---

# 文字檔案(.txt)讀寫
## 方法一:(用完要關閉檔案)
```python=
#方法一

f=open("test.txt","w")
f.write("hello\nit's a test2\nnice to meet you")  #寫進內容
f.close() #要記得close才能把文字寫進去!!

B=open("test.txt","r") #指定名稱不一定要是f 
text=B.read()    #讀取後存入text
text_lines=B.readlines()      #以行為單位讀取內容
B.close() #一樣記得CLOSE!
#print(B.read()) #不行print
print(text)    #print text中的內容
print(text_lines)   

```
寫進.txt內容:
hello
it's a test2
nice to meet you

```python=
印出結果:
hello
it's a test2        #from print(text)
nice to meet you

['hello\n', "it's a test2\n", 'nice to meet you']    #from print(text_lines) 
```
## 方法二:(在離開with這個區塊後自動關閉檔案)
```python=
with open("test.txt","r") as file:
    print(file.read())
```
在離開with這個區塊後自動關閉檔案，這代表了要注意縮排，如果要進行檔案編輯檢視，要包在with裡面做

## extra:寫入檔案到指定路徑(含創建資料夾):
在此以寫入圖片為例:
```python=
import os 
if not os.path.exists("folder_name"):    #如果在所在資料夾沒有該檔案，就創一個
    os.mkdir("folder_name")
    
path = os.path.abspath("folder_name")    #取得新資料夾的"絕對位置"
file=open(path+"/"+"file_name.jpg","wb")    #"開啟/新增一個檔案"(要寫入該新增檔案的完整路徑+格式)，"wb"為二進位制寫入
file.write(content)
file.close()
```

# EXCEL檔案讀寫(.xlsx)

要使用到"openpyxl"中的"load_workbook"這個函數
```python=
from openpyxl import load_workbook

workbook = load_workbook(filename="test.xlsx") #讀取xlsx檔案名為"test.xlsx"
sheet = workbook.active
value=sheet[""].value    #某特定格的value

for row in sheet.iter_rows(values_only=True):    #遍歷所有行
    print(row)
    
ws["A1"] = "Hello"    #寫入單個單元格
ws["B1"] = "World!"


data = ["This", "is", "a", "new", "row"]    
ws.append(data)    # 添加新行

wb.save("output_file.xlsx")    # 保存文件
```
# CSV讀寫
```python=
#CSV讀寫
import csv
with open("csv_test","w",newline="") as csv_file:    #創建一個csv_test檔案    #務必設置newline=""，避免作業系統兌換行處理不同的問題
    writein=csv.writer(csv_file,delimiter="x")    #delimiter=""，分隔物預設為','，也可自定
    writein.writerow(["1","2","3","4"])    #寫進行

    coordinates=[["A1","A2",'A3'],["B1",'B2','B3'],["C1",'C2','C3']]
    writein.writerows(coordinates)    #寫進多行
```