
file = open('C:/pythonEx/project/test.txt', 'w') # 'w'는 쓰기 권한으로 실행
strCnt = file.write('Hello Python!') # 말 그대로 쓰기만 가능(기존 내용 삭제 후 쓰기)
print(f'strCnt: {strCnt}') # 13
file.close()
strCnt에 담으면 문자열의 개수(int)가 담긴다.
변수에 할당하지 않고 실행만 해도 작동한다.
str 형태로 써야 한다(int 입력시 에러)
file = open('C:/pythonEx/project/test.txt', 'r') # 'r'은 읽기 권한
read = file.read()
print(read) #Hello Phthon!'
file.close()
[str].replace(a, b, c)
-> str에서 a라는 문자열을 찾아 b로 바꾼다.(3회)
uri = '[디렉토리]'
with open(uri + '5_037.txt', 'a') as f:
f.write('Hello Python!')
with open(uri + '5_037.txt', 'r') as f:
print(f.read()) # Hello Python!
with ~ as 구문으로 파일을 읽을 때, 변수에 저장해두면 with ~ as 구문 밖에서도 활용할 수 있다.
languages = ['c/c++', 'java', 'c#', 'python', 'javascript']
with open(uri + 'languages.txt', 'a') as f:
f.writelines(item + '\n' for item in languages)
조건식/조건문처럼 반복문도 한 줄 안에 명령어 사용 가능
scoreDic = {'kor': 85, 'eng': 85,'mat': 85,'sci': 85,'his': 85}
with open(uri + 'scores.txt', 'w') as f:
print(scoreDic, file=f)
print() 함수의 인자로 file= 부분을 추가해 텍스트파일 안에 출력문 그대로 저장할 수 있다.
[str].split(a) : a라는 문자를 기준으로 str을 나눠 list 형태로 담는다.
[str].strip(a) : str문의 맨 앞뒤에 a 문자를 삭제한다.(맨 앞뒤에 있는 겨우에만 삭제)