python - 读取python文件并使用输入

标签 python error-handling readfile

嗨,作为我的代码的一部分,我需要读取一个python文件,但我一直遇到错误:

other options:    {'input': 'dutch_training.txt\nenglish_training.txt\ndutch1.txt\ndutch_training.txt\nenglish_training.txt\ndutch_1.txt\n3\n.4\ndutch_training.txt\nenglish_training.txt\nenglish_1.txt\n4\n.3\ndutch_training.txt\nenglish_training.txt\ndutch_2.txt\n8\n.3\nabc\ndef\nexit\n'}
FileNotFoundError(2, 'No such file or directory')
result_code classify_unknown_text_cut   testingFailed   1
我搜索了谷歌,发现我可以使用:
os.path.abspath
这是我的代码:
def classify_unknown_text():
    a=1
    while a==1:

       file_1=os.path.abspath(input("Please enter the filename for language 1: "))
       file_2=os.path.abspath(input("Please enter the filename for language 2: "))
       clssify_file=os.path.abspath(input("Please enter the filename to classify: "))
       if clssify_file=="exit":
           a+=1
           return
       if os.path.isfile(file_1)==False or os.path.isfile(file_2)==False or os.path.isfile(clssify_file)==False:
            print("File error: some files do not exist.")

       else:
          max_length_ngram_1=int(input("Please enter the maximal length of the n-gram: "))
          threshold_1=float(input("Please enter threshold value between 0 and 0.5: "))
          file_for_dict1=open(file_1,"r")
          file_for_dict2=open(file_2,"r")
          file3_text=open(clssify_file,"r")
          text_dict_1=file_for_dict1.read()
          text_dic_2=file_for_dict2.read()
          text=file3_text.read()

          dict1=compute_ngrams_frequency(text_dict_1,max_length_ngram_1)
          dict2=compute_ngrams_frequency(text_dic_2,max_length_ngram_1)
          result=classify_language(text,dict1,dict2,threshold_1)
          if result==1:
             print("I believe the text matches the language in"+file_1)
          if result==2:
             print("I believe the text matches the language in"+file_2)

          if result==0:
             print("Sorry, I could not figure this one out!")
             #classify_unknown_text()
但是我仍然不断遇到同样的错误,我不知道该怎么办?谢谢

最佳答案

如果我没看错,os.path.abspath仅返回存储文件的绝对路径。如果您想打开一个文件并阅读甚至编写它,则可以执行以下操作:

#Opens file in read mode
file = open("/path/to/your/file", 'r')
如果要确定文件的扩展名以确保仅读取.py文件,则可以执行以下操作:
import os

file_extension = os.path.splitext('/path/to/file')[1]

#Check for extension
if(file_extension == '.py'):
    file_open = open('/path/to/file')
不知道我是否提供帮助,但我希望如此!

关于python - 读取python文件并使用输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65306658/

相关文章:

python - 如何在 Pyramid 中通过 POST 提交请求?

python - 如果我们只有类(class)名称,请单击链接

android - 异常尝试调用虚拟方法 - WebView Android

java - 如何找到file.txt的最大和最小数字?

android - 如何从android中的手机内存中读取文件?

linux - 读取具有多个字段的csv文件

python - 运行 heroku local 时出错

python - GTK3+ 和 Python 中的线程同步

c# - ASP.NET MVC自定义错误处理Application_Error Global.asax?

c - C 中的错误处理 : unable to malloc in nested function