Python 只读打印仅打印字符
我在Python IDLE中运行这段代码,它只返回指定的字母数量,而不是指定的行Python 只读打印仅打印字符,python,Python,我在Python IDLE中运行这段代码,它只返回指定的字母数量,而不是指定的行 if os.path.exists(saveDir + name + '.txt') == True: print('welcome back ' + name + '.') file = open(saveDir + name + '.txt') race = file.readline(1) else: race = intro() 当我打印race变量时,它显示为G(输入
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline(1)
else:
race = intro()
当我打印race变量时,它显示为G(输入名为Grant)。
文本文件如下所示
Grant
Human
我做错了什么?你是想读一行还是所有的行
file.readline()
将以字符串形式返回文件的第一行。如果再次调用,它将返回第二行,依此类推。您还可以使用file.readlines()
将文件的所有行作为列表加载,然后使用[0]
或[1]
获取第一个或第二个元素,因此file.readlines()[1]
将生成“Human”。race=file.readline(1)
返回行的1个字节(字符)(请参阅)。您希望返回整行,因此调用race=file.readline()
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline() # this reads one line at a time
raceType = file.readline() # this will give you the second line (human)
else:
race = intro()