在python中使用read()读取预先格式化的文件

2024-10-04 09:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

作为python的第一个项目,我正在尝试构建一个基于文本的小游戏。我决定把我的故事和内容写在文本文件里。我设计的游戏,使每个字符从文件中读取,并立即打印到屏幕上。你知道吗

def load_Intro():
liOb = open('loadgame.txt','r')
while True:
    ch = liOb.read(1)
    sys.stdout.write(ch)
    time.sleep(0.002)
    sys.stdout.flush()
    if ch == "\n": continue
    elif ch is None: break

print("\n")

但是,我的文本文件有多个段落,由一行或两行分隔,还有一些是自己的格式。例如,以下摘录自尚未最终确定的intr:

You are Max, a college student who lives a very ordinary life. One day, you decide to get out of this ordinary life and do something worth adventurous and be proud of! You skipped college for a week and worked overtime in your workplace, just to get enough money. For the past 1 week, you worked 16 hours a day, and had saved enough money for a cozy little vacation in the small town of Belleyard Upon Tyne. You pack your bags, and leave your house the next day.

Since you had to spend your money wisely, you decide to spend your days in a older hotel. You checked in a hotel called The Silver Mare. Your first two days were spent awesome. However this morning, after you wake up, you wake up feeling tired. Not only that, few times you felt someone following and creeping behind you. You looked back multiple times...... only to notice there's no one there. You ignored that feeling away as hangover due and prepare to enjoy your remaining holidays.

Date : October 21, 1997

{More Content}

当程序运行时,它可以很好地读取第一段。纠正我,如果我错了,最后一个条件检测到没有更多的字符检测,并卡在循环中。我需要帮助弄清楚如何读取和显示文件的内容完全相同的格式,我的文件是写在字符,直到文件结束字符。你知道吗


Tags: andofthetoinyou内容your
1条回答
网友
1楼 · 发布于 2024-10-04 09:27:11

为什么要一个字一个字地读?一次将其全部读入缓冲区,然后逐字符显示

import sys
import time

liOb = open('loadgame.txt','r')
content=str(liOb.read())

for i in range(len(content)):
    sys.stdout.write(content[i])
    time.sleep(0.002)
    sys.stdout.flush()

相关问题 更多 >