2014-09-22 33 views
0

在Python 2.6中:沒有這樣的文件或目錄或類型錯誤:強迫爲Unicode:需要字符串或緩衝區,列表中找到

我一直沒能實現任何迴應其他職位的這個錯誤,使它工作,所以我需要我的代碼直接幫助。我知道蟒蛇的基礎知識,我想我自己寫的腳本

  1. 打開一個文件夾
  2. 列表中的文件夾中的所有文件
  3. 打開這些文件逐一在每個計算文件唯一條目。

我創建一個字典,每個條目存儲爲一個鍵,值是每個條目存在的總次數。然後我要求打印字典的長度以知道有多少個唯一條目。該字典的作品,但通過該文件夾循環不。基本上,它告訴我,有沒有這樣的文件或目錄或以下錯誤:

#!/usr/bin/python  
    import sys 
    import os 

    # Takes files in a folder and counts unique records in each file, returns the number of each record followed by the name of the file 
    ##usage: perl countunique.py folder 
    folder = (sys.argv[1]) 
    list = open(os.listdir(folder), "rU") 

    for filename in list: 
     count = {} 
     for gene in filename: 
      if not gene in count : 
        count[gene]=1 
      else: 
        count[gene]+=1   
    print("There are {0} unique entries in {1}".format(len(count.keys()), f)) 

名單=開放(os.listdir(文件夾),「汝」)

類型錯誤:強迫爲Unicode:需要字符串或緩衝區,列表中找到

預先感謝您

編輯:

我也嘗試:

folder = (sys.argv[1]) 
list = os.listdir(folder) 
for filename in list: 
    file = open(filename, "rU") 
    count = {} 
    for gene in file: 
      if not gene in count : 
        count[gene]=1 
      else: 
        count[gene]+=1 

    print("There are {0} unique entries in {1}".format(len(count.keys()), filename)) 

,我得到這個錯誤: 文件=打開(文件名, 「汝」) IO錯誤:[錯誤2]沒有這樣的文件或目錄: 'file1.renamed'

file1.renamed實際上是該文件夾,所以我不知道爲什麼它無法找到它。

+0

'os.listdir'返回一個列表;你不能「打開」一個列表。 – jonrsharpe 2014-09-22 11:02:26

+0

好@jonrsharpe我嘗試了一些不同的東西 - 編輯原始文章 – user3691288 2014-09-22 11:22:22

+0

請編輯問題以使其更加連貫 - 現在有一小部分內容與當前問題無關。另外,你應該做一些研究 - 是Python目錄中的目錄嗎?爲什麼不使用完全合格的位置消除歧義? – jonrsharpe 2014-09-22 11:23:50

回答

0

解決:

#!/usr/bin/python 
import sys 
import os 

folder = sys.argv[1] 
for root, dirs, files in os.walk(folder): 
    for filename in files: 
      filePath = folder + '/' + filename 
      file = open(filePath, "rU") 
      count = {} 
      for gene in file: 
        if not gene in count : 
          count[gene]=1 
        else: 
          count[gene]+=1  
      print("There are {0} unique entries in {1}".format(len(count.keys()), filename)) 
相關問題