---
# System prepended metadata

title: Python學習日記 檔案操作
tags: [Python學習]

---

---
tags: Python學習
---
<style>
    .topic{
        color:#fa7f20;
        font-weight:bold;
    }
    .blue{
        color:#2f7cf7;
    }
</style>

# Python學習日記 檔案操作
>參考資料 - Python王者歸來 洪錦魁著

## <span class="topic">取得目前工作目錄</span>
```python=
import os
print(os.getcwd())
```

<br />

## <span class="topic">取得目前工作目錄的絕對路徑</span>
#### 目前工作目錄  
```python=
import os
print(os.path.abspath('.'))

> C:\Users\xxxx
```
#### 目前檔案的絕對路徑  
```python=
import os
print(os.path.abspath('xxx.py'))

> C:\Users\xxxx\xxx.py
```

<br />

## <span class="topic">檢查路徑是否存在</span>
#### os.path.exists(<span class="blue">path</span>) 判斷路徑是否存在
#### os.path.isabs(<span class="blue">path</span>) 判斷路徑是否為絕對路徑
#### os.path.isdir(<span class="blue">path</span>) 判斷路徑是否為資料夾
#### os.path.isfile(<span class="blue">path</span>) 判斷路徑是否為檔案

<br />

## <span class="topic">檔案與資料夾的操作</span>
#### mkdir(<span class="blue">path</span>) 建立path資料夾
#### rmdir(<span class="blue">path</span>) 刪除path的空資料夾
#### chdir(<span class="blue">path</span>) 將工作資料夾更改至path
#### remove(<span class="blue">path</span>) 刪除path檔案
#### rename(old_path, <span class="blue">new_path</span>) 將檔案更名為new_path


<br />

## <span class="topic">檔案讀取</span>
#### 讀取整個檔案  
```python=
file _file = open(path)
data = _file.read()
_file.close()
```
#### 逐行讀取檔案  
```python=
with open(path) as _file:
    for line in _file:
        print(line)
```
```python=
with open(path) as _file:
   data = _file.readlines()
```

#### 分批讀取檔案  
```python=
chunk = 100
msg = ''
with open(path) as _file:
    while True:
        txt = _file.read(chunk)
        if not txt:
            break
        msg += txt
print(msg)
```
<br />

## <span class="topic">檔案寫入</span>
```python=
x = 100
with open(path, 'w') as _file:
    _file.write(str(x))
```

<br />


## <span class="topic">CSV檔案處理 with Pandas</span>
#### 檔案讀取  
```python=
import os
import pandas as pd
path = os.path.join('c:' + os.sep, 'Users', 'XXXX', 'Desktop', 'data.csv')
dt = pd.read_csv(path)
```


#### 檔案寫入  
```python=
import os
import pandas as pd

#讀取
path = os.path.join('c:' + os.sep, 'Users', 'XXXX', 'Desktop', 'data.csv')
dt = pd.read_csv(path)

#寫入
toPath = os.path.join('c:' + os.sep, 'Users', 'XXXX', 'Desktop', 'output.csv')
dt.tocsv(toPath)
```