Python/알면 쓸모있는 잡다한 코드

Read File 파이썬 파일 읽기 / encoding error utf

joannekim0420 2021. 8. 23. 15:35
728x90

- open() function
= open(path_to_file, mode)

Mode Description
'r' open for text file for reading txt
'w' open a text file for writing text
'a' open a text file for appending text

 

text methods descriptions
read() read all text from a file into a string. 
readline() read the text file line by line and return all the lines as strings
readlines() read all the lines of the text file and return as a list of strings

f.close() -> 필수로 해줘야 파일이 닫힌다.

 

f = open ("C:\Users\~~~abc.txt","r",encoding='utf-8')

lines = f.readlines()

: abc 라는 텍스트 파일을 "r" 읽겠다. encoding 은 가장 기본적인 utf-8로 지정.

f라는 변수명으로 파일을 읽었으므로, 파일을 다룰 때는 f.readlines()처럼 f 변수를 이용한다. 

 

 

 

- with open() function

: f.close() 로 파일을 닫지 않아도 저절로 닫힘.

 

with open(path_to_file) as f:

         read_all_to_string = f.read()
with open('path') as f:         
         readlines_as_listofstrings = f.readlines()

for line in readlines_as_listofstrings :
      print(line)

<more concise way to read text line>

with open('path/python.txt', encoding='utf-8') as f:
         for line in f:
                print(line)

 

ENCODING ERROR!

 

'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

 

utf-8 으로 읽을 수 없는 파일이라고 뜬다면, utf-16으로 수정하면 된다. 

 

'utf-16' codec can't decode byte ~

그런데 간혹 여러파일을 동시에 읽다가 어떤 파일을 utf-8 로 읽을 수 없고, 어떤 파일은 utf-16으로 읽을 수 없다고 뜬다면!!

try:
  fread = open(in_path, "r",encoding="utf-8")
  lines = fread.readlines()
except:
  fread = open(in_path, "r",encoding="utf-16")
  lines = fread.readlines()