티스토리 뷰

python file을 생성하고 파일 내용 출력하는 함수 만들기

permission denied(권한 없음)이 나오면 관리자 권한으로 idea를 실행할 것.

python으로 데이터를 분석 할 때 file을 읽어와서 분석하는 경우가 많은데 약간 헷갈리는게 있어서 정리해 보았다.

일단 파일 저장하기
1
2
with open("./hello.txt", mode="w+") as f:
    f.write("hello \n")
cs


파일에서 한줄씩 불러와서 []로 받기
1
2
3
4
f1 = open("./hello.txt", mode='r')
lines = f1.readlines()
 
print(lines)
cs

파일 전체 불러오기
1
2
file = open("./exchange_rate.json","r")
print(file.read())
cs


파일에 여러줄 저장하기
1
2
3
4
5
6
7
import random
 
file_name = "./save_line.txt"
f1 = open(file_name, mode='w+')
for item in range(010):
    f1.write(str(random.randint(1100)) + "\n")
f1.close()
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#c:\에 a.txt 생성하고 파일에 내용을 기록
#mode='x'는 파일이 있으면 에러가 남 
f1 = open("c:/a.txt", mode='w+')
 
f1.write("lee 80 90 95 \n")
f1.write("kim 85 70 75 \n")
f1.close()
 
 
 
def getFileContents(file_path="c:/a.txt"):
    "file의 경로를 받아서 내용을 돌려주는 함수"
    f1 = open(file_path, mode='r', encoding='utf-8')
    return f1.read()
 
file_path = "c:/a.txt"
contents = getFileContents(file_path)
 
print(getFileContents.__doc__)
print(type(contents))
print("-----------", file_path, "의 내용 -------------")
print(contents)
cs


result


c:\


a.txt



shell




end.




공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함