우리가 익히 알고 있는 파일에 대해 알아보자
오늘은 텍스트 파일에 대해서만 알아보겠다
파일이란?
컴퓨터 보조장치에 저장되는 데이터를 담는 논리적인 저장 용기
./temp/a.text >> c:/users/ycho/temp/a.text)
../a.text >> c:/users/a.text) #지금보다 상위 '..' 사용
파일_변수 = open(파일_이름)
f = open("C:\temp\data.text")
파일_변수 = close()
f.close()
f= open("t.txt", "w") #파일에 텍스트 쓰기
f.write("hello world")
f.close
f = open("t.txt")
s = f.read()
print(s)
f.close
>> hello world
예시 파일 내용:
Hello, world!
This is a file.
It has multiple lines.
#1 readline 예시
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line, end='/')
line = file.readline()
#2 readlines 예시
with open('example.txt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line, end='/')

파일_변수 = open("파일 이름", 'a')
f.write(' ') #파일에 내용 추가로 쓰기
f = open('t.txt', 'w')
f.write('I know how it feels to have a broken heart')
f.close() # 내용 저장 후 닫기
with open("data.txt", "a", encoding="utf-8") as f:
f.write("Here comes to the end.\n"
with open("t.txt") as f:
for line in f:
print(line, end = '')
# close()를 따로 부르지 않아도 된다
f = open(filename, encoding = 'utf-8')
with open('example.txt', encoding = 'utf-8') as f:
s= f.read()
print(s)
def write_file():
text = input("저장할 문자열을 입력하세요: ")
with open('output.txt','w', encoding = 'utf-8') as f:
f.write(text)
print("저장완료")
write_file()

def read_file():
with open('output.txt','r') as f:
s = f.read()
print(s)
read_file()

def add_line():
with open('output.txt','w') as f:
while True:
txt = input("추가할 문자열을 입력하세요(중단하려면 'stop입력'): ")
if txt == 'stop':
break
f.write(txt+ '\n')
add_line()

def count_line():
count = 0
txt = input("카운트 할 단어를 입력하세요: ")
with open('output.txt','r') as f:
content = f.read()
count = content.count(txt)
print(f"{txt} 카운트 수: {count}")
count_line()

lineNumber = 1
found = False
file_name = input("검색할 파일 이름을 입력하세요: ")
findStr = input("검색할 문자열을 입력하세요: ")
with open(file_name,'r') as f:
line = f.readline()
while line:
if findStr in line:
found = True
print(f"{lineNumber}: {line.strip()}")
lineNumber +=1
line = f.readline()
if not found:
print("해당 문자열을 찾지 못했습니다")
break
