상세 컨텐츠

본문 제목

[PYTHON] 파이썬 파일 입출력

PYTHON/기본

by ranlan 2021. 4. 20. 19:39

본문

728x90

파일 읽기

* 한글깨짐 - encoding='UTF-8' 추가

 

data.txt

  hello
  world
  this is python
  my name is juran

 

with open('data.txt', 'r', encoding='UTF-8') as f:

    print(type(f)) # <class '_io.TextIOWrapper'>
    
    for line in f:
        print(line)
f = open('data.txt', 'r', encoding='UTF-8')
 
print(f.tell()) # 0
s1 = f.read(1)
print(s1) # h

print(f.tell()) # 1
s2 = f.readline()
print(s2) # ello\n
 
print(f.tell()) # 6
s3 = f.readlines()
print(s3) # ['world\n', 'this is python\n', 'my name is juran']

f.close()

 

메서드

read(n)  파일 스트림으로부터 해당 위치까지 문자 n개(n바이트) 읽음
 인자에 아무것도 없을 시 모든 문자를 읽음
 문자 n개 반환
readline()  해당 위치에서부터 한 줄의 문자열을 읽어옴
 '\n' 개행이 있을 때까지 문자열을 읽어옴
 문자열 반환
readlines()  해당 위치에서부터 파일의 모든 문자열을 읽어옴(개행 포함)
 문자열 리스트 반환
seek()  해당 위치로 파일의 커서를 옮김
 파일의 맨 처음 위치는 0
tell()  현재 커서의 위치 반환

파일 쓰기

with open("new_file.txt", "w") as f:
    f.write("Hello world!") 
    f.write("\nMy name is Juran!")
f = open('test.txt', 'w', , encoding='UTF-8')
 
f.write('hello')
f.write('\world')

f.writelines('a', 'b', 'c', 'd') # abcd
f.writelines('\n'.join(['a', 'b', 'c', 'd'])) # a\nb\nc\nd
 
f.close()

 

메서드

write()  인자로 받은 문자열 파일 작성
 직접 개행을 넣어줘야 함
writelines()  문자열 리스트를 한줄에 작성
 직접 개행을 넣어줘야 함

 

파일 입출력에서 자주 쓰이는 메서드 

 

strip

문자열 앞, 뒤의 공백제거(' ', '\t', '\w') strip

for line in f:
    print(line.strip())
    
my_str = "      abc    def    "
pirnt(my_str.strip()) # abc    def

 

split

문자열을 리스트로 분리

my_string = "1. 2. 3. 4. 5. 6"
print(my_string.split(".")) # ['1', ' 2', ' 3', ' 4', ' 5', ' 6']
print(my_string.split(". ")) # ['1', '2', '3', '4', '5', '6']

full_name = "lim, juran"
name_data = full_name.split(", ")
last_name = name_data[0] # juran
first_name = name_data[1] # lim

# 공백으로 분리
numbers = "    \n\n   2   \t   3 \n  5  7  11  \n\n".split()
print(numbers) # ['2', '3', '5', '7', '11']

print(numbers[0] + numbers[3]) # 27
print(int(numbers[0]) + int(numbers[3])) # 9

 

 

728x90

관련글 더보기

댓글 영역