2011-08-24 82 views
0

我想遍歷數字.rtf文件和每個文件:讀取文件,執行一些操作,然後將新文件作爲具有相同名稱的純文本文件寫入子目錄作爲原始文件,但帶有.txt擴展名。我遇到的問題是文件命名。Python的文件命名問題

如果一個文件名爲foo.rtf,我希望子目錄中的新文件是foo.txt。這裏是我的代碼:

import glob 
import os 
import numpy as np 


dir_path = '/Users/me/Desktop/test/' 
file_suffix = '*.rtf' 
output_dir = os.mkdir('sub_dir') 
for item in glob.iglob(dir_path + file_suffix): 
    with open(item, "r") as infile: 
     reader = infile.readlines() 
     matrix = [] 
     for row in reader: 
      row = str(row) 
      row = row.split() 
      row = [int(value) for value in row] 
      matrix.append(row) 
     np_matrix = np.array(matrix) 
     inv_matrix = np.transpose(np_matrix) 
     new_file_name = item.replace('*.rtf', '*.txt') # i think this line is the problem? 
     os.chdir(output_dir) 
     with open(new_file_name, mode="w") as outfile: 
      outfile.write(inv_matrix) 

當我運行這段代碼,我得到一個類型錯誤:

TypeError: coercing to Unicode: need string or buffer, NoneType found

如何解決我的代碼寫入新文件到一個子目錄,並改變從文件擴展名.rtf到.txt?謝謝您的幫助。

+2

我們可以得到一個堆棧跟蹤? –

+0

似乎不太可能標記的行會引發該錯誤。 – geoffspear

+0

你介意標記一個答案被接受或沒有答案告訴你你需要什麼嗎? –

回答

3

相反的item.replace,檢查出一些功能,在os.path模塊(http://docs.python.org/library/os.path.html)。它們用於拆分和重新組合部分文件名。例如,os.path.splitext會將文件名分割爲文件路徑和文件擴展名。

比方說,你有一個文件/tmp/foo.rtf,並且希望將其移動到/tmp/foo.txt

old_file = '/tmp/foo.rtf' 
(file,ext) = os.path.splitext(old_file) 
print 'File=%s Extension=%s' % (file,ext) 
new_file = '%s%s' % (file,'.txt') 
print 'New file = %s' % (new_file) 

或者,如果你想要的行版本:

old_file = '/tmp/foo.rtf' 
new_file = '%s%s' % (os.path.splitext(old_file)[0],'.txt') 
2

我從來沒有用過水珠,但這裏不使用模塊的另一種方式:
您可以輕鬆地剝離使用

name = name[:name.rfind('.')] 

後綴,然後添加新的後綴:

name = name + '.txt' 

爲什麼不使用函數?

def change_suffix(string, new_suffix): 
    i = string.rfind('.') 
    if i < 0: 
     raise ValueError, 'string does not have a suffix' 
    if not new_suffix[0] == '.': 
     new_suffix += '.' 
    return string[:i] + new_suffix 
0

glob.iglob()產生路徑名,不帶字符'*'。 所以你行應該是:

new_file_name = item.replace('.rtf', '.txt') 

考慮用一個文件名和使用「路徑」爲指向一個文件的完整路徑更清晰的名稱(儲備「文件名」工作;利用「path_original」而不是「項目」 ),os.extsep(在Windows)和os.path.splitext() '':

path_txt = os.extsep.join([os.path.splitext(path_original)[0], 'txt']) 

現在所有的最好的提示: numpy的大概可以read your file directly

data = np.genfromtxt(filename, unpack=True) 

(見here

爲了更好地瞭解您的TypeError來自,/用你的代碼在以下try except塊:

try: 
    (your code) 
except: 
    import traceback 
    traceback.print_exc() 
+0

對您的評論進行了小修改:'os.sep'在Windows中是\\,而不是'.' –

+0

謝謝!更正於回答 – Remi

+0

來自glob文檔(http://docs.python.org/library/glob.html#glob.glob)「路徑名可以是絕對的(如/usr/src/Python-1.5/Makefile)或相對路徑(比如../../Tools/*/*.gif),並且可以包含shell風格的通配符「。如果我理解正確,路徑名可以包含「*」字符,但不能保證。 – Wilduck