-
working with file🐍 파이썬/파이썬 기본 문법 2022. 7. 17. 07:39
create file
# opening a file in write mode will either create a new file (if the file does not exist) # or overwrite an existing one f = open('test.txt', 'w')
read file
f = open('test.txt', 'r') contents = f.read() # read the entire file content print(contents) contents = f.read(10) # read only the first 10 characters of the file print(contents) line = f.readline() # read first line of the file print(line) for line in f.readlines(): # read the contents of the file line by line print(line)
write file
# creating a new file for writing (or over writing) f = open('test.txt', 'w') f.write('First line') f.write('Still the First line\n') f.write('second line\n') # open file for appending with 'a’ f = open('test.txt', 'a') f.write('This string is added...') f.write('to the existing') # to save the changes to the file and make # it available for reading, it must be closed! f.close()
with statement
: The withstatement will bind the opened file handle to a variable and it will automatically handle the closingat the end of the block.
with open('test.txt', 'w') as f: f.write('...') with open('test.txt', 'r') as f: print(f.read())
'🐍 파이썬 > 파이썬 기본 문법' 카테고리의 다른 글
함수를 함수의 변수로 넘기기 (0) 2022.07.18 [Function] 함수란 (0) 2022.07.18 False in Python (0) 2022.07.17 isinstance(x,y) (0) 2022.07.17 [string] 문자열 자주 쓰이는 문법 정리 (0) 2022.07.17