在Android平板电脑上打开Qpthon 3中的文本文件

我是学习编码的新手,从Python 2.7开始。 如何在Qpython 3中打开文本文件?

# Opening a file

inp = raw_input ("Enter a File Name: ")

#Optional guardian to capture incorrect filenames
try:

fhand = open('words.txt')
except:
    print "Invalid Filename "
    exit()
#End of Guardian code

count = 0
for line in fhand:
    count = count + 1
print "Line Count", count

我从这里得到的是错误信息。


错误消息IOError: [Errno 2] No such file or directory: 'words.txt'表示Python在找到它的地方找不到文件words.txt

Python在哪里寻找文件?

如果传递给open()的字符串看起来像一个绝对路径,那么Python就会在那里看到。 'words.txt'看起来不像绝对路径,因此它被视为相对路径。 相对于什么? 除了你可能期望的, 不是相对于你的python源文件,而是相对于当前的工作目录

如果您从交互式shell中调用脚本,则可能知道适用的当前工作目录。 我不知道在用Qpython开发时是否有人可以做这件事。 但如果不是,不要担心。

import os
print os.getcwd()

将输出当前工作目录的路径,这应该有助于确定将文件放在哪里或如何访问它。

缩进在python中很重要

输出实际的异常消息对调试很有帮助。 但是,因为你有一个除了块,它可能不是你想要的。 如果要输出“无效的文件名”,则必须修复try块的缩进。 ( fhand = open('words.txt')必须缩进才能try: 。)

我实际上对此有点惊讶,你没有收到一条消息: IndentationError: expected an indented block

适当的异常处理

只抓住你可以(并且)正确处理

请注意,一旦try块被修复(参见上面的部分), except块将捕获它中的每个异常,即使它不是IOError: [Errno 2] No such file or directory 。 这意味着即使在open时出现完全不同的问题时,也会输出“无效的文件名”,如耗尽RAM来分配。

因此,请尝试捕捉您将在except块中处理的具体错误。

使用错误消息的stderr

print >> sys.stderr, "Invalid Filename "

您可以打印到标准错误流而不是标准输出流。 如果脚本的标准输出被重定向到文件,这将很有用。

使用用户输入

您当前正在使用硬编码的文件名,并且在提示时不执行用户Enter a File Name: 。 我想,一旦你完成调试,你会用imp代替硬编码的文件名,这里保存着用户输入。 请注意,通过替换它,您将允许用户不仅指定文件名,而且指定脚本将访问的文件路径(绝对或相对于当前工作目录)。 这可能或可能不是你想要允许的。


在qpython的路径中没有问题。 斜杠“/”可以通过“es文件浏览器”找到并在生根后更改并写入。 我使用“os.system('sh')”进入andrio sonsole .type“python ** .py”我可以工作,当然,你应该把** .py加入到Divice并改变它的权限(通常是预先设定的)

Es下载:http://www.estrongs.com/?lang=en

使用follow来改变路径:(键入python控制台)

os.chdir( “****”)

****应该是/ storage / emulated / 0 / py像这样。 你应该一个一个打字,或者它不工作,你知道我的意思。 我做的。

新:::重新安装控制台时,它会回到“/"..T_T


我认为qpython在这里有一个问题,我一直试图弄清楚自己,但可能是一个未解决的qpython问题

print(os.getcwd()) only prints a single slash '/' for me so I have had to resolve to putting the full path in

rdir = "/mnt/sdcard/com.hipipal.qpyplus/projects3/fileio/ "
with open(rdir+"test.txt", "wt") as out_file:
    out_file.write("This text is going to _____________the out filen look at it and see")

你可以这样读写。

链接地址: http://www.djcxy.com/p/54715.html

上一篇: Opening Text files in Qpthon 3 on android tablet

下一篇: Download all the links(related documents) on a webpage using Python