KR_FileIO - somaz94/python-study GitHub Wiki
ํ์ด์ฌ์์๋ open()
ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ํ์ผ์ ์ด ์ ์๋ค.
# ๊ธฐ๋ณธ ํ์ผ ์ด๊ธฐ/๋ซ๊ธฐ
file = open('example.txt', 'w') # ์ฐ๊ธฐ ๋ชจ๋๋ก ํ์ผ ์ด๊ธฐ
file.close() # ํ์ผ ๋ซ๊ธฐ
# with ๋ฌธ์ ์ฌ์ฉํ ํ์ผ ์ฒ๋ฆฌ (๊ถ์ฅ)
with open('example.txt', 'w') as file:
file.write('Hello, World!') # ์๋์ผ๋ก ํ์ผ์ด ๋ซํ
# ์ธ์ฝ๋ฉ ์ง์
with open('unicode.txt', 'w', encoding='utf-8') as file:
file.write('์๋
ํ์ธ์!') # ์ ๋์ฝ๋ ๋ฌธ์ ์ฒ๋ฆฌ
# ์๋ฌ ์ฒ๋ฆฌ
try:
with open('nonexistent.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("ํ์ผ์ด ์กด์ฌํ์ง ์์ต๋๋ค.")
except PermissionError:
print("ํ์ผ์ ์ ๊ทผํ ๊ถํ์ด ์์ต๋๋ค.")
except IOError as e:
print(f"์
์ถ๋ ฅ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {e}")
-
'r'
: ์ฝ๊ธฐ ๋ชจ๋ (๊ธฐ๋ณธ๊ฐ) - ํ์ผ์ด ์์ผ๋ฉด ์๋ฌ ๋ฐ์ -
'w'
: ์ฐ๊ธฐ ๋ชจ๋ (ํ์ผ ๋ด์ฉ ๋ฎ์ด์ฐ๊ธฐ) - ํ์ผ์ด ์์ผ๋ฉด ์๋ก ์์ฑ -
'a'
: ์ถ๊ฐ ๋ชจ๋ (ํ์ผ ๋์ ๋ด์ฉ ์ถ๊ฐ) - ํ์ผ์ด ์์ผ๋ฉด ์๋ก ์์ฑ -
'x'
: ๋ฐฐํ์ ์์ฑ ๋ชจ๋ - ํ์ผ์ด ์ด๋ฏธ ์์ผ๋ฉด ์๋ฌ ๋ฐ์ -
'b'
: ๋ฐ์ด๋๋ฆฌ ๋ชจ๋ (ํ ์คํธ๊ฐ ์๋ ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ์ฒ๋ฆฌ) -
't'
: ํ ์คํธ ๋ชจ๋ (๊ธฐ๋ณธ๊ฐ) -
'+'
: ์ฝ๊ธฐ/์ฐ๊ธฐ ๋ชจ๋ (์: 'r+', 'w+', 'a+')
# ๊ฐ ๋ชจ๋ ์์
with open('file.txt', 'r') as f: # ์ฝ๊ธฐ ์ ์ฉ
content = f.read()
with open('file.txt', 'w') as f: # ์ฐ๊ธฐ ์ ์ฉ (๋ฎ์ด์ฐ๊ธฐ)
f.write('์๋ก์ด ๋ด์ฉ')
with open('file.txt', 'a') as f: # ์ถ๊ฐ ๋ชจ๋
f.write('๊ธฐ์กด ๋ด์ฉ์ ์ถ๊ฐ')
try:
with open('new_file.txt', 'x') as f: # ๋ฐฐํ์ ์์ฑ
f.write('์ ํ์ผ ๋ด์ฉ')
except FileExistsError:
print("ํ์ผ์ด ์ด๋ฏธ ์กด์ฌํฉ๋๋ค")
with open('binary.dat', 'wb') as f: # ๋ฐ์ด๋๋ฆฌ ์ฐ๊ธฐ
f.write(b'\x00\x01\x02\x03')
with open('file.txt', 'r+') as f: # ์ฝ๊ธฐ+์ฐ๊ธฐ
content = f.read()
f.write('๋ ๋ง์ ๋ด์ฉ')
# ๋จ์ ํ
์คํธ ์ฐ๊ธฐ
with open('test.txt', 'w', encoding='utf-8') as f:
f.write('Hello\n')
f.write('World\n')
# print() ํจ์๋ก ํ์ผ์ ์ฐ๊ธฐ
with open('test.txt', 'w', encoding='utf-8') as f:
print('Hello', file=f)
print('World', file=f)
print('์๋
ํ์ธ์', '๋ฐ๊ฐ์ต๋๋ค', sep=', ', file=f)
# ๋ฆฌ์คํธ์ ๋ด์ฉ์ ํ์ผ์ ์ฐ๊ธฐ
lines = ['Line 1', 'Line 2', 'Line 3']
with open('test.txt', 'w', encoding='utf-8') as f:
f.writelines(line + '\n' for line in lines)
# ๋์
๋๋ฆฌ ๋ฐ์ดํฐ ์ฐ๊ธฐ
data = {'name': 'ํ๊ธธ๋', 'age': 30, 'city': '์์ธ'}
with open('data.txt', 'w', encoding='utf-8') as f:
for key, value in data.items():
f.write(f"{key}: {value}\n")
# ์ถ๊ฐ ๋ชจ๋๋ก ํ์ผ์ ๋ด์ฉ ์ถ๊ฐ
with open('log.txt', 'a', encoding='utf-8') as f:
import datetime
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
f.write(f"[{now}] ๋ก๊ทธ ํญ๋ชฉ ์ถ๊ฐ\n")
# ํ์ผ ์ฐ๊ธฐ ์์น ์ ์ด
with open('position.txt', 'w+', encoding='utf-8') as f:
f.write("์ฒซ ๋ฒ์งธ ์ค\n")
f.write("๋ ๋ฒ์งธ ์ค\n")
position = f.tell() # ํ์ฌ ์์น ์ ์ฅ
print(f"ํ์ฌ ์์น: {position} ๋ฐ์ดํธ")
f.seek(0) # ํ์ผ์ ์ฒ์์ผ๋ก ์ด๋
f.write("๋ฎ์ด์ด ์ฒซ ๋ฒ์งธ ์ค\n") # ์ฒซ ์ค ๋ฎ์ด์ฐ๊ธฐ
f.seek(0, 2) # ํ์ผ์ ๋์ผ๋ก ์ด๋ (0์ ์์น, 2๋ ํ์ผ ๋ ๊ธฐ์ค)
f.write("์ธ ๋ฒ์งธ ์ค\n")
# ์ ์ฒด ๋ด์ฉ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# ํน์ ํฌ๊ธฐ๋งํผ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
chunk = f.read(10) # ์ฒ์ 10๋ฐ์ดํธ๋ง ์ฝ๊ธฐ
print(chunk)
next_chunk = f.read(10) # ๋ค์ 10๋ฐ์ดํธ ์ฝ๊ธฐ
print(next_chunk)
# ํ ์ค์ฉ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
line = f.readline() # ์ฒซ ๋ฒ์งธ ์ค
print(line, end='') # ์ค๋ฐ๊ฟ ๋ฌธ์๊ฐ ์ด๋ฏธ ํฌํจ๋์ด ์์
second_line = f.readline() # ๋ ๋ฒ์งธ ์ค
print(second_line, end='')
# ๋ชจ๋ ์ค์ ๋ฆฌ์คํธ๋ก ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(f"ํ์ผ์ ์ด ์ค ์: {len(lines)}")
for i, line in enumerate(lines, 1):
print(f"์ค {i}: {line.strip()}") # strip()์ผ๋ก ์ค๋ฐ๊ฟ ์ ๊ฑฐ
# for ๋ฌธ์ผ๋ก ํ์ผ ์ฝ๊ธฐ (๋ฉ๋ชจ๋ฆฌ ํจ์จ์ )
with open('test.txt', 'r', encoding='utf-8') as f:
for line in f: # ํ์ผ ๊ฐ์ฒด๋ ์ดํฐ๋ฌ๋ธํ์ฌ ํ ์ค์ฉ ์ํ
print(line.strip())
# ์์น ์ง์ ํ์ฌ ์ฝ๊ธฐ
with open('test.txt', 'r', encoding='utf-8') as f:
f.seek(10) # 10๋ฒ์งธ ๋ฐ์ดํธ๋ก ์ด๋
partial = f.read(20) # 20๋ฐ์ดํธ ์ฝ๊ธฐ
print(partial)
# ํฐ ํ์ผ ํจ์จ์ ์ผ๋ก ์ฒ๋ฆฌ
def count_lines(filename):
count = 0
with open(filename, 'r', encoding='utf-8') as f:
for _ in f:
count += 1
return count
# ์ฒญํฌ ๋จ์๋ก ํ์ผ ์ฝ๊ธฐ
def read_in_chunks(filename, chunk_size=1024):
"""์ง์ ๋ ํฌ๊ธฐ์ ์ฒญํฌ ๋จ์๋ก ํ์ผ ์ฝ๊ธฐ"""
with open(filename, 'rb') as f: # ๋ฐ์ด๋๋ฆฌ ๋ชจ๋ ์ฌ์ฉ
while True:
chunk = f.read(chunk_size)
if not chunk: # ํ์ผ ๋์ ๋๋ฌ
break
yield chunk
# ์ฌ์ฉ ์์
# for chunk in read_in_chunks('large_file.txt'):
# process_data(chunk)
import os
import shutil
# ํ์ผ ์กด์ฌ ์ฌ๋ถ ํ์ธ
if os.path.exists('test.txt'):
print('ํ์ผ์ด ์กด์ฌํฉ๋๋ค')
else:
print('ํ์ผ์ด ์กด์ฌํ์ง ์์ต๋๋ค')
# ํ์ผ์ธ์ง ๋๋ ํ ๋ฆฌ์ธ์ง ํ์ธ
if os.path.isfile('test.txt'):
print('test.txt๋ ํ์ผ์
๋๋ค')
elif os.path.isdir('test_dir'):
print('test_dir์ ๋๋ ํ ๋ฆฌ์
๋๋ค')
# ํ์ผ ์ ๋ณด ํ์ธ
if os.path.exists('test.txt'):
size = os.path.getsize('test.txt') # ํ์ผ ํฌ๊ธฐ(๋ฐ์ดํธ)
mtime = os.path.getmtime('test.txt') # ์์ ์๊ฐ (Unix ํ์์คํฌํ)
import datetime
mod_time = datetime.datetime.fromtimestamp(mtime)
print(f"ํ์ผ ํฌ๊ธฐ: {size} ๋ฐ์ดํธ")
print(f"์ต์ข
์์ ์๊ฐ: {mod_time}")
# ํ์ผ ์ญ์
if os.path.exists('temp.txt'):
os.remove('temp.txt')
print('ํ์ผ์ด ์ญ์ ๋์์ต๋๋ค')
# ํ์ผ ์ด๋ฆ ๋ณ๊ฒฝ
if os.path.exists('old.txt'):
os.rename('old.txt', 'new.txt')
print('ํ์ผ ์ด๋ฆ์ด ๋ณ๊ฒฝ๋์์ต๋๋ค')
# ํ์ผ ๋ณต์ฌ
import shutil
if os.path.exists('source.txt'):
shutil.copy('source.txt', 'destination.txt') # ํ์ผ ๋ณต์ฌ
shutil.copy2('source.txt', 'destination2.txt') # ๋ฉํ๋ฐ์ดํฐ ํฌํจ ๋ณต์ฌ
# ๋๋ ํ ๋ฆฌ ์์ฑ
if not os.path.exists('new_directory'):
os.makedirs('new_directory', exist_ok=True) # ์ค์ฒฉ ๋๋ ํ ๋ฆฌ ์์ฑ
print('๋๋ ํ ๋ฆฌ๊ฐ ์์ฑ๋์์ต๋๋ค')
# ๋๋ ํ ๋ฆฌ ์ญ์
if os.path.exists('empty_dir') and os.path.isdir('empty_dir'):
os.rmdir('empty_dir') # ๋น ๋๋ ํ ๋ฆฌ๋ง ์ญ์ ๊ฐ๋ฅ
print('๋น ๋๋ ํ ๋ฆฌ๊ฐ ์ญ์ ๋์์ต๋๋ค')
# ๋๋ ํ ๋ฆฌ์ ๋ด์ฉ ๋ชจ๋ ์ญ์
if os.path.exists('dir_with_files') and os.path.isdir('dir_with_files'):
shutil.rmtree('dir_with_files')
print('๋๋ ํ ๋ฆฌ์ ๋ด์ฉ์ด ๋ชจ๋ ์ญ์ ๋์์ต๋๋ค')
# ํ์ผ ๊ฒฝ๋ก ๋ค๋ฃจ๊ธฐ
filename = 'document.txt'
directory = 'projects/python'
full_path = os.path.join(directory, filename) # 'projects/python/document.txt'
print(f"์ ์ฒด ๊ฒฝ๋ก: {full_path}")
# ๊ฒฝ๋ก ๋ถํด
path = '/home/user/documents/report.pdf'
dirname = os.path.dirname(path) # '/home/user/documents'
basename = os.path.basename(path) # 'report.pdf'
filename, ext = os.path.splitext(basename) # ('report', '.pdf')
print(f"๋๋ ํ ๋ฆฌ: {dirname}")
print(f"ํ์ผ๋ช
: {filename}, ํ์ฅ์: {ext}")
import csv
# CSV ํ์ผ ์ฐ๊ธฐ
data = [
['์ด๋ฆ', '๋์ด', '์ง์
'],
['๊น์ฒ ์', 28, '๊ฐ๋ฐ์'],
['์ด์ํฌ', 32, '๋์์ด๋'],
['๋ฐ์ง๋ฏผ', 24, 'ํ์']
]
with open('people.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data) # ๋ชจ๋ ํ ํ ๋ฒ์ ์ฐ๊ธฐ
# CSV ํ์ผ ์ฝ๊ธฐ
with open('people.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
header = next(reader) # ํค๋ ํ ์ฝ๊ธฐ
print(f"ํค๋: {header}")
for row in reader:
print(f"{row[0]}๋ {row[1]}์ธ {row[2]}์
๋๋ค.")
# ๋์
๋๋ฆฌ๋ก CSV ๋ค๋ฃจ๊ธฐ
dict_data = [
{'์ด๋ฆ': '๊น์ฒ ์', '๋์ด': 28, '์ง์
': '๊ฐ๋ฐ์'},
{'์ด๋ฆ': '์ด์ํฌ', '๋์ด': 32, '์ง์
': '๋์์ด๋'},
{'์ด๋ฆ': '๋ฐ์ง๋ฏผ', '๋์ด': 24, '์ง์
': 'ํ์'}
]
with open('people_dict.csv', 'w', newline='', encoding='utf-8') as f:
fieldnames = ['์ด๋ฆ', '๋์ด', '์ง์
']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader() # ํค๋ ์ฐ๊ธฐ
writer.writerows(dict_data) # ๋์
๋๋ฆฌ ๋ชฉ๋ก ์ฐ๊ธฐ
# ๋์
๋๋ฆฌ๋ก CSV ์ฝ๊ธฐ
with open('people_dict.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['์ด๋ฆ']}๋ {row['๋์ด']}์ธ {row['์ง์
']}์
๋๋ค.")
import json
# JSON ํ์ผ ์ฐ๊ธฐ
data = {
'name': 'ํ๊ธธ๋',
'age': 30,
'city': '์์ธ',
'hobbies': ['๋
์', '๋ฑ์ฐ', 'ํ๋ก๊ทธ๋๋ฐ'],
'active': True,
'scores': {
'math': 85,
'english': 92,
'python': 98
}
}
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
# ensure_ascii=False: ํ๊ธ ๋ฑ ์ ๋์ฝ๋ ๋ฌธ์ ๊ทธ๋๋ก ์ ์ฅ
# indent=4: ๋ค์ฌ์ฐ๊ธฐ๋ก ๊ฐ๋
์ฑ ํฅ์
# JSON ํ์ผ ์ฝ๊ธฐ
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print(f"์ด๋ฆ: {loaded_data['name']}")
print(f"์ทจ๋ฏธ: {', '.join(loaded_data['hobbies'])}")
print(f"ํ์ด์ฌ ์ ์: {loaded_data['scores']['python']}")
# JSON ๋ฌธ์์ด ๋ค๋ฃจ๊ธฐ
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)
parsed_data = json.loads(json_str)
print(parsed_data['city'])
# ๋ฐ์ด๋๋ฆฌ ํ์ผ ์ฐ๊ธฐ
with open('binary.dat', 'wb') as f:
f.write(b'\x48\x65\x6c\x6c\x6f') # 'Hello'์ ๋ฐ์ดํธ ํํ
# ๋ฐ์ด๋๋ฆฌ ํ์ผ ์ฝ๊ธฐ
with open('binary.dat', 'rb') as f:
data = f.read()
print(data) # b'Hello'
print(data.decode('utf-8')) # 'Hello'
# ๊ตฌ์กฐํ๋ ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ
import struct
# ์ ์์ ๋ฌธ์์ด ํจํน
with open('packed.bin', 'wb') as f:
# 'i'๋ 4๋ฐ์ดํธ ์ ์, '5s'๋ 5๋ฐ์ดํธ ๋ฌธ์์ด
packed_data = struct.pack('i5s', 42, b'Hello')
f.write(packed_data)
# ์ธํจํน
with open('packed.bin', 'rb') as f:
data = f.read()
unpacked = struct.unpack('i5s', data)
print(f"์ ์: {unpacked[0]}, ๋ฌธ์์ด: {unpacked[1].decode('utf-8')}")
# ์ด๋ฏธ์ง ํ์ผ ์ฒ๋ฆฌ ์์
def copy_image(src, dst):
"""์ด๋ฏธ์ง ํ์ผ์ ๋ณต์ฌํ๋ ํจ์"""
with open(src, 'rb') as src_file:
with open(dst, 'wb') as dst_file:
dst_file.write(src_file.read())
# copy_image('source.jpg', 'copy.jpg')
import os
# ํ์ฌ ์์
๋๋ ํ ๋ฆฌ ํ์ธ
current_dir = os.getcwd()
print(f"ํ์ฌ ๋๋ ํ ๋ฆฌ: {current_dir}")
# ๋๋ ํ ๋ฆฌ ๋ณ๊ฒฝ
# os.chdir('../') # ์์ ๋๋ ํ ๋ฆฌ๋ก ์ด๋
# print(f"๋ณ๊ฒฝ๋ ๋๋ ํ ๋ฆฌ: {os.getcwd()}")
# ๋๋ ํ ๋ฆฌ ๋ด์ฉ ๋์ด
entries = os.listdir('.') # ํ์ฌ ๋๋ ํ ๋ฆฌ ๋ด์ฉ
print("ํ์ฌ ๋๋ ํ ๋ฆฌ ๋ด์ฉ:")
for entry in entries:
if os.path.isfile(entry):
print(f"ํ์ผ: {entry}")
elif os.path.isdir(entry):
print(f"๋๋ ํ ๋ฆฌ: {entry}")
# ํน์ ํ์ฅ์ ํ์ผ ์ฐพ๊ธฐ
def find_files_by_extension(directory, extension):
"""์ง์ ๋ ๋๋ ํ ๋ฆฌ์์ ํน์ ํ์ฅ์๋ฅผ ๊ฐ์ง ํ์ผ ์ฐพ๊ธฐ"""
result = []
for entry in os.listdir(directory):
full_path = os.path.join(directory, entry)
if os.path.isfile(full_path) and entry.endswith(extension):
result.append(full_path)
return result
# ์ฌ๊ท์ ์ผ๋ก ๋๋ ํ ๋ฆฌ ํ์
def list_all_files(directory):
"""๋๋ ํ ๋ฆฌ ๋ด์ ๋ชจ๋ ํ์ผ์ ์ฌ๊ท์ ์ผ๋ก ๋์ด"""
for root, dirs, files in os.walk(directory):
for file in files:
full_path = os.path.join(root, file)
print(full_path)
# ํน์ ํจํด์ ํ์ผ ์ฐพ๊ธฐ
import glob
python_files = glob.glob('*.py') # ํ์ฌ ๋๋ ํ ๋ฆฌ์ ๋ชจ๋ .py ํ์ผ
print("Python ํ์ผ:")
for file in python_files:
print(file)
# ์ฌ๊ท์ ์ผ๋ก ํน์ ํจํด ์ฐพ๊ธฐ
all_python_files = glob.glob('**/*.py', recursive=True)
print("๋ชจ๋ ํ์ ๋๋ ํ ๋ฆฌ์ Python ํ์ผ:")
for file in all_python_files:
print(file)
โ ํ์ผ ์ฒ๋ฆฌ ๋ชจ๋ฒ ์ฌ๋ก:
- ํญ์
with
๋ฌธ ์ฌ์ฉํ์ฌ ํ์ผ์ ์๋์ผ๋ก ๋ซํ๊ฒ ํ๋ค - ํ ์คํธ ํ์ผ ์ฒ๋ฆฌ ์ ํญ์ ์ธ์ฝ๋ฉ์ ๋ช ์ํ๋ค (์ฃผ๋ก 'utf-8')
- ํ๊ธ ๋ฑ ์ ๋์ฝ๋ ์ฒ๋ฆฌ ์
encoding='utf-8'
์ฌ์ฉ์ด ํ์์ ์ด๋ค - ์ ์ ํ ์์ธ ์ฒ๋ฆฌ๋ก ํ์ผ ์ ๊ทผ ์ค๋ฅ์ ๋์ํ๋ค
- ํ์ผ ๊ฒฝ๋ก๋ ๋ฌธ์์ด ์ฐ๊ฒฐ์ด ์๋
os.path.join()
์ฌ์ฉ์ ๊ถ์ฅํ๋ค - ํฐ ํ์ผ์ ํ ๋ฒ์ ๋ชจ๋ ์ฝ์ง ๋ง๊ณ ํ ์ค์ฉ ๋๋ ์ฒญํฌ ๋จ์๋ก ์ฒ๋ฆฌํ๋ค
- CSV, JSON ๋ฑ ํน์ ํ์์ ์ ์ฉ ๋ชจ๋์ ํ์ฉํ๋ค
-
os.path
ํจ์๋ฅผ ์ด์ฉํด ๊ฒฝ๋ก๋ฅผ ์์ ํ๊ฒ ๋ค๋ฃฌ๋ค - ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ๋ ํญ์ ๋ฐ์ด๋๋ฆฌ ๋ชจ๋('rb', 'wb')๋ก ์ฒ๋ฆฌํ๋ค
- ํ์ผ ์ด๋ฆ์ ๋ณ์๊ฐ ํฌํจ๋ ๊ฒฝ์ฐ f-string ๋ณด๋ค๋
os.path.join()
์ ์ฌ์ฉํ๋ค