Python Read&Write

yoonlucky7ยท2021๋…„ 6์›” 25์ผ
0

Read & write


๐Ÿ“ ํŒŒ์ผ ์ฝ๊ธฐ ๋ฐ ์“ฐ๊ธฐ

๐Ÿ“Œ ์ฝ๊ธฐ ๋ชจ๋“œ : r, ์“ฐ๊ธฐ ๋ชจ๋“œ : w, ์ถ”๊ฐ€ ๋ชจ๋“œ : a, ํ…์ŠคํŠธ ๋ชจ๋“œ : t, ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ชจ๋“œ : b

๐Ÿ’ก Code

# ํŒŒ์ผ ์ฝ๊ธฐ ๋ฐ ์“ฐ๊ธฐ
# ์ฝ๊ธฐ ๋ชจ๋“œ : r, ์“ฐ๊ธฐ ๋ชจ๋“œ : w, ์ถ”๊ฐ€ ๋ชจ๋“œ a, ํ…์ŠคํŠธ ๋ชจ๋“œ t, ๋ฐ”์ด๋„ˆ๋ฆฌ ๋ชจ๋“œ b
# ์ƒ๋Œ€ ๊ฒฝ๋กœ('../, ./'), ์ ˆ๋Œ€ ๊ฒฝ๋กœ('C:\yoonl\example..')
# ํŒŒ์ผ ์ฝ๊ธฐ(Read)
# ์˜ˆ์ œ1
f = open('./resource/it_news.txt','r',encoding = 'UTF-8')
print(dir(f))
print(f.encoding)
print(f.name)
print(f.mode)
cts=f.read()
print(cts)
f.close()

# ์˜ˆ์ œ2
with open('./resource/it_news.txt','r',encoding = 'UTF-8') as f:
    c = f.read()
    print(c)
    print(iter(c))
    print(list(c))

print()

# ์˜ˆ์ œ3
# read() : ์ „์ฒด ์ฝ๊ธฐ, read(10) : 10Byte
with open('./resource/it_news.txt','r',encoding = 'UTF-8') as f:
    c = f.read(20)
    print(c)
    c = f.read(20)
    print(c)
    f.seek(0,0)
    c = f.read(20)
    print(c)
print()
#  ์˜ˆ์ œ4
# readline : ํ•œ ์ค„ ์”ฉ ์ฝ๊ธฐ
with open('./resource/it_news.txt','r',encoding = 'UTF-8') as f:
    line = f.readline()
    print(line)
    line = f.readline()
    print(line)
print()
# ์˜ˆ์ œ 5
# readlines : ์ „์ฒด๋ฅผ ์ฝ์€ ํ›„ ๋ผ์ธ ๋‹จ์œ„ ๋ฆฌ์ŠคํŠธ๋กœ ์ €์žฅ
with open('./resource/it_news.txt','r',encoding = 'UTF-8') as f:
    cts = f.readlines()
    print(cts)
    print()
    for c in cts:
        print(c,end='')
print()

# ํŒŒ์ผ ์“ฐ๊ธฐ(write)

# ์˜ˆ์ œ1
with open('./resource/contents1.txt','w',encoding = 'UTF-8') as f:
    f.write('I love python\n')
with open('./resource/contents1.txt','a',encoding = 'UTF-8') as f:
    f.write('I love python2\n')
# ์˜ˆ์ œ3
# writelines : ๋ฆฌ์ŠคํŠธ -> ํŒŒ์ผ
with open('./resource/contents2.txt','w') as f:
    list = ['Orange\n','Apple\n','Banana\n','Melon\n']
    f.writelines(list)
with open('./resource/contents3.txt','w') as f:
    print('Test Text Write!',file=f)
    print('Test Text Write!',file=f)
    print('Test Text Write!',file=f)
profile
์„ธ์ƒ์ด ๋” ๋‚˜์•„์ง€๊ธฐ๋ฅผ ๋ฐ”๋ผ๋Š” ๋งˆ์Œ์œผ๋กœ ๊ฐœ๋ฐœ์— ์ž„ํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€