在android平板电脑上以Qpthon 3打开文本文件

在android平板电脑上以Qpthon 3打开文本文件,android,qpython,Android,Qpython,我刚开始学习编码并开始学习Python 2.7。如何在Qpython3中打开文本文件 # 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

我刚开始学习编码并开始学习Python 2.7。如何在Qpython3中打开文本文件

# 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]没有这样的文件或目录:“words.txt”
意味着Python无法在查找文件的位置找到该文件

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

如果从交互式shell调用脚本,则可能知道适用的当前工作目录。我不知道在使用Qpython开发时是否可以/确实这样做。但如果没有,不要担心

import os
print os.getcwd()
will,这将帮助您确定文件的存放位置或访问方式

python中的缩进问题 输出实际异常的消息有利于调试。但由于您有一个except块,它可能不是您想要的。如果希望输出“无效文件名”,则必须修复try块的缩进。(
fhand=open('words.txt')
必须相对于
try:
缩进)

事实上,我有点惊讶,这个程序运行时,您没有收到一条消息说
IndentationError:应该是一个缩进的块

正确的异常处理 只抓住你能正确处理的事情 请注意,一旦
try
块被修复(请参见上面的部分),
except
块将捕获其中的每个异常,即使它不是
IOError:[Errno 2]没有这样的文件或目录。这意味着您将输出“无效文件名”,即使在
open
中出现完全不同的问题时,例如要分配的RAM不足

因此,请尝试捕获将在
块中处理的特定错误,但
块除外

对错误消息使用stderr 与

您可以使用它而不是标准输出流。如果脚本的标准输出被重定向到文件,这将非常有用

使用用户输入
您当前使用的是硬编码的文件名,当提示输入文件名时,对用户输入的名称不做任何操作。
。我猜调试完成后,您将用保存用户输入的
imp
替换硬编码文件名。请注意,只需替换它,用户不仅可以指定文件名,还可以指定脚本随后将访问的文件路径(绝对路径或相对于当前工作目录的路径)。这可能是您希望允许的,也可能不是。我认为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 file\n look at it and see")

您可以这样读写。

qpython的路径没有问题。 斜杠“/”可以通过“es文件浏览器”找到,并在生根后更改和写入。 我使用“os.system('sh')”进入andrio sonsole。键入“python**.py”我可以工作,当然,您应该将**.py放入Divice并更改其权限(通常是pretermit)

下载:

使用follow更改路径:(在python控制台中键入)

os.chdir(“****”)

****应该是这样的/storage/simulated/0/py。你应该一个接一个地打字,否则不行,你知道我的意思。 我做到了


新:::重新启动控制台时,它会返回“/”。T\u T

您会收到什么错误消息?错误消息最后一行是:IOError:[Errno 2]没有这样的文件或目录:“words.txt”
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 file\n look at it and see")