본문 바로가기
WEB/Python

[Python] 파일 읽기 open().read()

by Ellen571 2020. 8. 22.

[생활코딩] 활용 - 파일 기능을 이용해 본문 구현

 

 

open()는 파일명과 파일 처리방식을 입력 받아 결과를 준다.

open(파일명, 읽기모드) = open('file', 'r') --- r은 기본값이라 생략가능

open(파일명, 쓰기모드) = open('file', 'w')

open(파일명, 추가모드) = open('file', 'a')

 

open().read()는 파일의 내용을 문자열로 반환한다.

 

 

[실습]

1. data폴더에 HTML, CSS, Javascript 파일 생성

 

2. index.py 에서 data 폴더의 파일 읽어 description에 담기

#!/usr/local/bin/python3
print("content-type:text/html; charset=UTF-8\n")

import cgi
form = cgi.FieldStorage()

if 'id' in form:
    pageId = form["id"].value
    description = open('data/'+pageId).read()
else:
    pageId = 'Welcome'
    description = 'Hello Python'

print('''<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.py">WEB</a></h1>
  <ol>
    <li><a href="index.py?id=HTML">HTML</a></li>
    <li><a href="index.py?id=CSS">CSS</a></li>
    <li><a href="index.py?id=JavaScript">JavaScript</a></li>
  </ol>
  <h2>{title}</h2>
  <p>{desc}</p>
</body>
</html>
'''.format(title=pageId, desc=description))
반응형

'WEB > Python' 카테고리의 다른 글

[Python] form 값 처리하기(FieldStorage, open, Location)  (0) 2020.08.23
[Python] 파일목록 읽기 - listdir, 반복문 - for  (0) 2020.08.23
[Python] cgi.FieldStorage()  (0) 2020.08.22
CGI?  (0) 2020.08.21
Python 설치 및 실행(Mac OS)  (0) 2020.08.21