1. open()
#open() : ํ์ผ ์ด๊ธฐ
>>> path = '/Users/eunhye/Desktop/Workspace/test.txt'
>>> file = open(path)
2. read()
#read() : ํ์ผ ์ฝ๊ธฐ
#ํ
์คํธ ํ์์ผ๋ก ํ์ค์ ๋ณด์ฌ์ค
>>> fileContent = file.read()
>>> fileContent
'test'
#readlines() : ํ์ค์ ํ์ผ ์ฝ๊ธฐ
#๋ฆฌ์คํธ ํ์์ผ๋ก ๋ณด์ฌ์ค
>>> numberFile = open(path2)
>>> numberContent = numberFile.read()
>>> numberContent
'1\n2\n3\n4\n5\n'
>>> numberFile = open(path2)
>>> numberFile.readlines()
['1\n', '2\n', '3\n', '4\n', '5\n']
3. wirte()
#wirte(), w ๋ชจ๋ : ๋ฎ์ด์ฐ๊ธฐ
>>> file = open(path, 'w')
>>> file.write('Hello World!\n')
13
#close() ํจ์ ํตํด์ ์ข
๋ฃ ํ ์ผ๋ฐ ๋ชจ๋๋ก open()
>>> file.close()
>>> file = open(path)
>>> fileContent = file.read()
>>> fileContent
'Hello World!\n'
#wirte(), a ๋ชจ๋ : ์ด์ด์ฐ๊ธฐ
>>> file = open(path, 'a')
>>> file.write('I\'m eunhye!')
11
#close() ํจ์ ํตํด์ ์ข
๋ฃ ํ ์ผ๋ฐ ๋ชจ๋๋ก open()
>>> file.close()
>>> file = open(path)
>>> fileContent = file.read()
>>> fileContent
"Hello World!\nI'm eunhye!"
4. shelve ๋ชจ๋ ์ฌ์ฉํ๊ธฐ
- ํ์ด์ฌ์ ๋ณ์๋ฅผ ์ ์ฅํ๋ ๋ชฉ์ ์ผ๋ก ์ฌ์ฉํ๋ฉฐ ์ด์ง ํ์ผ๋ก ์ ์ฅ
- ์๋ cat์ผ๋ก ๋ฌธ์๋ฅผ ์ด ๊ฒฝ์ฐ text ํ์ผ์ด ์๋ ์ด์ง ํ์ผ์ด๋ผ ๋ณด์ด์ง ์์
>>> import shelve
>>> os.getcwd()
'/Users/eunhye/Test'
#myinform์ด๋ผ๋ shelf file์ ๋ง๋ค์ด key : value ์
๋ ฅ
>>> shelfFile = shelve.open('myinform')
>>> shelfFile['name'] = 'eunhye'
>>> shelfFile['age'] = 27
>>> shelfFile['gender'] = 'female'
#shelf file์ type ํ์ธ ๊ฐ๋ฅ
>>> type(shelfFile)
<class 'shelve.DbfilenameShelf'>
#key : value ํ์ธ ๊ฐ๋ฅ
>>> list(shelfFile.keys())
['age', 'gender', 'name']
>>> list(shelfFile.values())
[27, 'female', 'eunhye']
>>> shelfFile['age']
27
>>> shelfFile['gender']
'female'
>>> shelfFile['name']
'eunhye'
5. pprint ๋ชจ๋ ์ฌ์ฉํ๊ธฐ
- ๋ฐ์ดํฐ๋ฅผ ๋ณด๊ธฐ ์ข๊ฒ ๊ต์ ํด์ ๋ณด์ฌ์ค
>>> import pprint
#๋ณด๊ธฐ ์ข๊ฒ ๊ต์ ํด์ ๋ณด์ฌ์ค
>>> temp = [{'age': 27, 'gender': 'female', 'name': 'eunhye'}, {'age': 26, 'gender': 'female', 'name': 'yeji'}]
>>> pprint.pprint(temp)
[{'age': 27, 'gender': 'female', 'name': 'eunhye'},
{'age': 26, 'gender': 'female', 'name': 'yeji'}]
>>> pprint.pformat(temp)
"[{'age': 27, 'gender': 'female', 'name': 'eunhye'},\n {'age': 26, 'gender': 'female', 'name': 'yeji'}]"
#ํ์ด์ฌ ํ์ผ์ ์์ฑํ์ฌ ๋ณ์๋ฅผ ์ ์ฅํด์ค ์ ์์
>>> file = open('informDic.py', 'w')
>>> file.write('informDic = ' + pprint.pformat(temp) + '\n')
114
>>> file.close()
#ํ์ด์ฌ ํ์ผ์ importํ์ฌ ์ฌ์ฉํ ์ ์์
>>> import informDic
#๋ฐ์ดํฐ ํ์ธ ๊ฐ๋ฅ
>>> informDic.informDic
[{'age': 27, 'gender': 'female', 'name': 'eunhye'}, {'age': 26, 'gender': 'female', 'name': 'yeji'}]
>>> informDic.informDic[0]
{'age': 27, 'gender': 'female', 'name': 'eunhye'}
>>> informDic.informDic[1]
{'age': 26, 'gender': 'female', 'name': 'yeji'}
>>> informDic.informDic[0]['name']
'eunhye'
'Programming > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ฌธ์์ด ๋ค๋ฃจ๊ธฐ (0) | 2021.08.09 |
---|---|
selenium ํตํด์ web crawling ํด์ slack ๋ฉ์ธ์ง ๋ณด๋ด๊ธฐ (0) | 2021.06.22 |
ํ์ผ ๊ฒฝ๋ก ์ด๋(copy, move)ํ๊ณ ์ญ์ (rm)ํ๊ณ ์์ถ(zip)ํ๊ธฐ (0) | 2021.06.22 |
OS ๋ชจ๋ (0) | 2021.06.16 |
์น ํฌ๋กค๋ง(BeautifulSoup) (0) | 2021.05.06 |