1. ํ์ผ ์
์ถ๋ ฅ(I/O - input/output)
์
๋ ฅ(input) ๊ธฐ์กด ํ์ผ ์ฝ์ด๋ค์ด๋ ๊ฒ
์ถ๋ ฅ(output) ํ์ผ์์ฑ, ๋ด์ฉ ์ถ๊ฐ๋ฅผ ๋งํ๋ค.
# ์ฒซ๋ฒ์งธ ๋ฐฉ๋ฒ file open
file = open('myFile.txt', 'wt')
print('myFile.txt ํ์ผ์ด ์์ฑ๋์์ต๋๋ค.')
file.close() # ๋ซ์์ค์ผ ํจ
# with ๋ฌธ - ์๋์ผ๋ก close()๋ฅผ ํด์ค๋ค.
with open('myFile.txt', 'wt') as file:
print('myFile.txt ํ์ผ์ด ์์ฑ๋์์ต๋๋ค.')
2. open ํจ์ ๋ชจ๋
w(write mode) : ์ฐ๊ธฐ ์ ์ฉ ๋ชจ๋ / ํ์ผ ์์ผ๋ฉด ์์ฑ
t(text mode) : ํด๋นํ์ผ์ ๋ฐ์ดํฐ๋ฅผ ํ
์คํธ ํ์ผ๋ก ์ธ์ํ๊ณ ์
์ถ๋ ฅ.
b(binary mode) : ํด๋น ํ์ผ์ ๋ฐ์ดํฐ๋ฅผ ๋ฐ์ด๋๋ฆฌ ํ์ผ๋ก ์ธ์ํ๊ณ ์
์ถ๋ ฅ.
file = open('hello.txt', 'wt', encoding='UTF-8')
file.write('์๋
ํ์ธ์.')
file.write('\n')
file.write('๋ฐ๊ฐ์ต๋๋ค.')
file.write('\n')
print('hello.txt ํ์ผ์ด ์์ฑ๋์์ต๋๋ค.')
file.close()
3. a (append mode) : ์ถ๊ฐ ๋ชจ๋
file = open('hello.txt', 'at', encoding='UTF-8')
file.write('Hello\n')
file.write('Nice to meet you\n')
print('hello.txt ํ์ผ์ ์๋ก์ด ๋ด์ฉ์ด ์ถ๊ฐ ๋์์ต๋๋ค.')
file.close()
4. r (read mode) : ์ฝ๊ธฐ ์ ์ฉ ๋ชจ๋ / ํ์ผ ์์ผ๋ฉด ์๋ฌ
๊ฒฝ๋ก
์ ๋๊ฒฝ๋ก ์) C://pstudy//PythonProject//Day07//Section13//hello.txt
์๋๊ฒฝ๋ก ์) /hello2.txt
../../resources/hello.txt
. -> ํ์ฌํด๋
.. -> ์์ํด๋
์ต์์ ๊ฒฝ๋ก(root) / ๋๋ C:/(์๋์ฐOS)
# file = open('/hello.txt', 'rt')
str = file.read()
print(str, end='')
file.close()
# print()
with open('hello.txt', 'rt') as file:
str = file.read()
print(str, end='')
5. file ๊ฐ์ฒด read() -> ์ ์ฒด ์ฝ์ด์ค๊ธฐ
read(์ธ์๊ฐ) -> ์ธ์๊ฐ ๋งํผ ์ฝ์ด์ค๊ธฐ
file = open('hello.txt', 'rt', encoding='UTF-8')
while True:
str = file.read(5)
if not str: # ์ฝ์ ๊ฐ์ด ์์ผ๋ฉด True
break
print(str)
file.close()
6. readline()
ํ์ผ์์ 1์ค์ ์ฝ๊ณ ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํด
with open('hello.txt', 'rt', encoding='UTF-8') as file:
while True:
str = file.readline()
if str == '':
break
print(str, end='')
7. with open('hello.txt', 'rt', encoding='UTF-8') as file:
line_list = file.readlines()
print(line_list)
for line in line_list:
print(line, end='')
8. with open('hello.txt', 'rt', encoding='UTF-8') as file:
line_list = file.readlines()
for no, line in enumerate(line_list):
print('{} {}'.format(no+1, line), end='')
9. import sys #OS(Operating System)
with open('hello.txt', 'rt', encoding='UTF-8') as file:
line_list = file.readlines()
sys.stdout.writelines(line_list) #์์คํ
์คํ ๋ค๋ ์์, ์ค ๋จ์๋ก ํ๋ฆฐํธ ํ ๊ฑฐ๋ ๋์ผ
#print(line_list)
'๐์น ๊ฐ๋ฐ(Web) > ๐ํ์ด์ฌ(Python)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ์ด์ฌ json (0) | 2023.02.08 |
---|---|
ํ์ผ๋ณต์ฌ/csvํ์ผ ์ฝ๊ธฐ ์ฐ๊ธฐ (0) | 2023.02.08 |
์ง์ญ๋ณ์(local) ์ ์ญ๋ณ์(global) (0) | 2023.02.01 |
datetime ๋ชจ๋ (0) | 2023.02.01 |
ํ์ด์ฌ time ๋ชจ๋ (0) | 2023.02.01 |