2014-07-11 76 views
-1

我是Python新手,我試圖從ftp目錄獲取文件。每次運行此代碼時都會出現此錯誤。當我運行它時,它讀取目錄中的所有文件,然後在callback = mylist[1]上給我一個錯誤。第一部分定義的功能,另一部分是我所說的文件:IndexError:從ftp讀取文件時字符串索引超出範圍

from ftplib import FTP 
    import os, sys 

    def rCallback3(filename): 
    new_filename = "rrrr/files/%s" % just_filename 
    retval = subprocess.call(["/usr/local/bin/r.py", filename]) 
    os.rename(filename, new_filename) 
    return retval 

我已刪除了部分代碼......

ftp = ftplib.FTP('192.192.0.195', 'ro', 'Password') 
files = ftp.dir() 
dirlist = ['/',rCallback3] 

while (True): 
    # Go through each of the directories 
    for mylist in dirlist: 
     check_dir = mylist[0] 
     callback = mylist[1]-- here i get this error 

     # get the list of files in the directory 
     filelist = os.listdir(check_dir) 
     for this_file in filelist: 
      if ((this_file == ".") or (this_file == "..") or (this_file == "donecsvfiles")or (this_file == "doneringofiles")): 
       print "Skipping self and parent" 
       continue 

      full_filename = "%s/%s"%(check_dir, this_file) 

      # Get the modification time of the file 
      first_stat = os.stat(full_filename)[8] 

      # Sleep for 1 second 
      time.sleep(1) 

      # Get the modification time again 
      second_stat = os.stat(full_filename)[8] 

      # If the modication time has not changed, then the file is stable 
      # and can be sent to the callback 
      if (first_stat == second_stat): 
       callback(full_filename) 

現在我得到這個錯誤。

{"iv": 
    { "result": "ok" } 
} 
Traceback (most recent call last): 
    File "/usr/local/bin/ringo.py", line 51, in <module> 
    reader = csv.reader(open(csvfile, 'r')) 
IOError: [Errno 21] Is a directory: '//tmp' 
Traceback (most recent call last): 
    File "./dirmon.py", line 83, in <module> 
    callback(full_filename) 
    File "./dirmon.py", line 46, in ringoCallback3 
    os.rename(filename, new_filename) 
OSError: [Errno 18] Invalid cross-device link 
+0

打印報表是你的朋友!在mylist in dirlist之後打印mylist:'你會看到它是'/',而不是一個列表。 – tdelaney

+0

@tdelaney:如果字符串更長,則不會發生聲明的錯誤... –

+0

@ScottHunter - 意思...,什麼?他會有同樣的錯誤,並且會在代碼中進一步發揮作用。打印語句仍然會顯示錯誤。 – tdelaney

回答

0

dirlist[0]是單字符的字符串('/'),所以mylist最初該字符串;因爲它只有1個字符,所以mylist[1]什麼也沒有。

也許你真的不想迭代dirlist,或者它應該是[['/',rCallback3]]

0

在節目的一開始是這樣的一行:

dirlist = ['/',rCallback3] 

這名dirlist分配到列表['/',ringoCallback3]。那麼你有一個for循環:

for mylist in dirlist: 

是遍歷dirlist並得到每個項目mylist

dirlist(因此第一個值爲mylist)的第一項是字符串'/'

所以,當Python的第一次遇到以下兩行:

check_dir = mylist[0] 
callback = mylist[1] 

它會將它們視爲等同於:

check_dir = '/'[0] 
callback = '/'[1] 

第二個引發IndexError因爲'/'只有一個字符,但您告訴Python在索引1處得到不存在的第二個字符:

>>> '/'[1] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: string index out of range 
>>> 
+0

謝謝icodez,但我只有一個目錄,其中有多個文件。當我使用callback = mylist [0]然後我得到Traceback(最近呼叫最後): 文件「./dirmon.py」,行83,在 回調(full_filename) TypeError:'str'對象不可調用 – shriyaj

相關問題