简体   繁体   English

file.read()在Python中不起作用

[英]file.read() doesn't work in Python

So I'm new to programming and I'm making a zork-type game as extracurricular practice. 因此,我是编程的新手,并且正在做一种课外练习的热衷型游戏。 And currently I'm trying to make a simple "load" function where python would extract the previously saved name and class of character. 目前,我正在尝试制作一个简单的“加载”功能,以便python提取以前保存的名称和字符类。 The code is this: 代码是这样的:

print "Enter savefile name: " 
save1 = raw_input("> ") + ".py"
load_data = open(save1, "r")
data = load_data.read()

However it doesn't read the file. 但是,它不会读取文件。 So if I'd write something like print data it would just skip the command, without any errors or anything really. 因此,如果我要编写类似print data ,它将跳过该命令,而不会出现任何错误或真正的错误。

I've been looking at this stupid piece of code for ages and can't figure out what's the problem with it. 多年来,我一直在看这段愚蠢的代码,无法弄清这是什么问题。 Please help! 请帮忙!

Thank you 谢谢

Have you checked at each stage that something is actually being returned. 您是否在每个阶段检查是否确实返回了某些东西。 Try something like so: 尝试这样的事情:

if save1:
    print "save1 is correct"

if load_data:
    print "load_data is correct"

if data:
    print "data has a value"

Try these lines after your code block. 在代码块之后尝试这些行。 This will help you identify where the error is, and once your problem is isolated you will be able to better search for what went wrong. 这将帮助您确定错误的出处,一旦问题被隔离,您将能够更好地搜索出问题所在。

This will create a text file with a custom name, if that's what you mean 如果这就是您的意思,这将创建一个带有自定义名称的文本文件

sname=str(input("Enter savefile name: "))
fw=open(sname+'.txt', 'w')
fw.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM