【问题标题】:write a function in JES that will distinguish type of file is chosen在 JES 中编写一个函数来区分选择的文件类型
【发布时间】:2015-03-08 07:10:18
【问题描述】:

"编写一个函数来获取文件名(使用pickAFile),然后识别它是图片还是声音文件,或者甚至是其他文件类型。然后文件应该被解释为图片,如果它的类型是jpg(然后打印适当的消息,然后退出)或声音,如果它的类型是wav(然后打印适当的消息,然后退出),如果它既不是图片也不是声音文件,则错误消息必须打印。此错误消息应包括文件的类型(或缺少类型,例如可能没有句点的文件名,例如ducksjpg)。请记住,文件类型可以是 2、3、4甚至更多的字母!”

所以这就是我到目前为止所想出来的并且它有效:

def sortoutfiles():
 f= pickAFile()
 print f
 filename=f
 if filename.endswith (".jpg"):
   print "It's a picture"
 if filename.endswith (".wav"):
   print " It's a sound"
 else:
   print"Oops! Did not choose a picture or a sound file"

由于某种原因,当我在第 5 行尝试使用 rfind-get 错误消息无效语法时,程序无法运行

def sortoutfiles():
   f= pickAFile()
   print f
   filename=f  
   if p=filename.rfind('.jpg'):
      print "It's a picture"
   if filename=f.rfind(".wav"):
      print " It's a sound"
   else:
      print"Oops! Did not choose a picture or a sound file"
here

谁能告诉我在使用 rfind 编写程序时我做错了什么?

【问题讨论】:

  • 把它分解成单独的任务,然后研究如何分别完成每个任务。解决第一个任务,然后研究下一个任务并将该功能添加到您的代码中。冲洗并重复,直到完成所有任务。如果您在此过程中遇到困难,您可以解释您遇到的问题,包含您遇到困难的相关代码,并提出具体问题。如果您根本无法开始,请向您的导师寻求帮助。

标签: jes


【解决方案1】:

Apco 1P00?

使用 rfind 找出文件扩展名

f = pickAFile()
p = f.rfind('.jpg') #finds if the file ends in .jpg
s = f.rfind('.wav') #finds if the file ends in .wav
length = len(f) #finds the length of the file name

以此为基础,然后使用 if 语句从这里开始。

回忆上一个实验。

>>> testString = 'abc DEf ghi ihg uVW xyz'
>>> print testString.find('k')
-1           #"Not found" can't be 0, so result is -1 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多