All Articles

Python - 반복문으로 글목록 만들기

  • data : 목록의 글을 저장한 폴더명
  • index.py : 초기 화면
  • 전체 코드
#!/usr/local/bin/python3
print("Content-Type: text/html")
print()
import cgi, os
 
files = os.listdir('date')
listStr = ''
for item in files:
    listStr = listStr + '<li><a href="index.py?id={name}">{name}</a></li>'.format(name=item)
     
form = cgi.FieldStorage()
if 'id' in form:
    pageId = form["id"].value
    description = open('data/'+pageId, 'r').read()
else:
    pageId = 'Welcome'
    description = 'Hello, web'
print('''<!doctype html>
<html>
<head>
  <title>WEB1 - Welcome</title>
  <meta charset="utf-8">
</head>
<body>
  <h1><a href="index.py">WEB</a></h1>
  <ol>
    {listStr}
  </ol>
  <h2>{title}</h2>
  <p>{desc}</p>
</body>
</html>
'''.format(title=pageId, desc=description, listStr=listStr))
import cgi, os

cgi, os라는 명령어로 묶여있는 모듈을 사용하겠다는 선언

 files = os.listdir('date')

listdir(path)은 경로로 주어진 딕셔너리 안에 있는 모든 엔트리 리스트를 출력한다.

for item in files:

files라는 리스트에 있는 값을 하나하나 꺼내서 item이라는 변수로 담는 것

for item in files:
    listStr = listStr + '<li><a href="index.py?id={name}">{name}</a></li>'.format(name=item)

str.format()은 파이썬 문자열 포매팅 방법 중 하나로, 중괄호 부분에 지정한 값을 반환한다.

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

open = (file name, mode)은 파일을 읽어오는 방식이다.
생성하고자 하는 파일이 index 파일과 다른 폴더에 있으면 '폴더명/'+파일명으로 지정한다.
위 코드는 id값이 있는 경우에 ‘data’ 디렉토리에서 파일을 ‘읽어오는’ 것이므로 모드는 ‘r’이다. 쓰기 모드는 ‘w’다.

파일명.read() 여기에서는 위에서 연 파일을 열기 위함이다. else 이후에는 페이지에 id 값이 없을 때 반환할 텍스트 입력한다.