【问题标题】:Opening Text files in Qpthon 3 on android tablet在 android 平板电脑上打开 Qpthon 3 中的文本文件
【发布时间】:2015-06-27 14:57:48
【问题描述】:

我刚开始学习编码并从 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'

标签: android qpython


【解决方案1】:

错误消息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()

output the current working directory's path,它应该可以帮助您确定将文件放在哪里或如何访问它。

缩进在 python 中很重要

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

我真的有点惊讶这个运行,你没有收到说IndentationError: expected an indented block的消息。

正确的异常处理

只抓住你能(和做)正确处理的事情

请注意,一旦try 块被修复(参见上面的部分),except 块将捕获其中的所有异常,即使它不是IOError: [Errno 2] No such file or directory。这意味着即使open 中存在完全不同的问题,您也会输出“Invalid Filename”,例如内存不足。

因此,请尝试捕获您将在 except 块中处理的特定错误。

使用 stderr 获取错误消息

print >> sys.stderr, "Invalid Filename "

can print to the standard error stream 而不是标准输出流。如果您的脚本的标准输出被重定向到一个文件,这将非常有用。

使用用户输入

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

【讨论】:

    【解决方案2】:

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

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

    使用follow改变路径:(在python控制台输入)

    os.chdir("****")

    **** 应该是这样的 /storage/emulated/0/py 。你应该一个一个地输入,否则它不起作用,你知道我的意思。 我做到了。

    New::: 当重新启动控制台时,它会回到“/”..T_T

    【讨论】:

      【解决方案3】:

      我认为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")
      

      你可以这样读写。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-31
        • 2018-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多