Python 隨筆 - file management: replace
===
###### tags: `Python`
Method 1 - Does not work
---
```python=
import os
f = open("data.txt", 'r')
output = open("data2.txt", 'w')
store = open("data_temp.txt", 'w+')
store.write(f.read().replace("Hand ",''))
output.write(store.read().replace("Material ",''))
f.close()
output.close()
store.close()
os.remove("data_temp.txt")
```
錯誤原因:
1. 若要重複讀取檔案,需要將指標回歸至檔案頭(自己的假設)
解決方法:在閱讀完畢執行 `f1.seek(0)`
1. 多執行緒問題
>就是你有一個中間檔,第一次取代完存在裡面,第二次取代的時候讀出,不過python的檔案讀寫不是原子性的,義思就是他可能在底層對某個檔案的讀寫是同時進行的,然後就會混亂XD
>[:linked_paperclips: stackoverflow.com/questions/1185660](https://stackoverflow.com/questions/1185660/python-is-os-read-os-write-on-an-os-pipe-threadsafe)
1. 檔案權限,參考以下網友整理不同Mode給予的權限
```
| Mode | r | r+ | w | w+ | a | a+ |
| :--------------------: | :--: | :--: | :--: | :--: | :--: | :--: |
| Read | + | + | | + | | + |
| Write | | + | + | + | + | + |
| Create | | | + | + | + | + |
| Cover | | | + | + | | |
| Point in the beginning | + | + | + | + | | |
| Point in the end | | | | | + | + |
```
[:linked_paperclips: stackoverflow.com/questions/6648493/](https://stackoverflow.com/questions/6648493/how-to-open-a-file-for-both-reading-and-writing)
Method 2 - Dummy answer to fix Method 1
---
```python=
import os
f = open("data.txt", 'r')
output = open("data2.txt", 'w')
store = open("data_temp.txt", 'w')
store.write(f.read().replace("Hand ",''))
store.close()
store = open("data_temp.txt", 'r')
output.write(store.read().replace("Material ",''))
f.close()
output.close()
store.close()
# if os.path.exists("demofile.txt"):
os.remove("data_temp.txt") # one file at a time
```
Method 3 - Works well
---
```python=
checkWords = ("Hand ","Material ")
repWords = ("","")
f1 = open('data.txt', 'r')
f2 = open('data2.txt', 'w')
for line in f1:
for check, rep in zip(checkWords, repWords):
line = line.replace(check, rep)
f2.write(line)
f1.close()
f2.close()
```
[:linked_paperclips: stackoverflow.com/questions/51240862/](https://stackoverflow.com/questions/51240862/find-and-replace-multiple-words-in-a-file-python)
Method 4
---
```python=
import re
s = "old_text1 old_text2"
s1 = re.sub("old_text" , "new_text" , s)
```
[:linked_paperclips: stackoverflow.com/questions/51240862/](https://stackoverflow.com/questions/51240862/find-and-replace-multiple-words-in-a-file-python)
Method 5
---
```python=
def replace_all(text, dic):
# for i, j in dic.iteritems():
for i, j in dict.items(): #dict.items() for python 3
text = text.replace(i, j)
return text
```
[:linked_paperclips: stackoverflow.com/questions/51240862/](https://stackoverflow.com/questions/51240862/find-and-replace-multiple-words-in-a-file-python)