2015-11-03 88 views
0

我想通過使用Visual Studio 2015和Python 3.4編寫一個快速腳本來解析Recuva輸出日誌文件來自學python。VS2015 + Python 3.4文件IO

Starting Point Promo 2013 - Compilation-HD.mp4 15020953 M:\Videos For Future Use\

注意輸入文件在文件名,文件大小和輸出路徑之間有多個空格。

import os 
import re 

fileName = os.path.join("C:\\", "Users", "temp", "Downloads", "deleted_files.txt") 

pattern = r""" 
    (.*) 
    \s{2,} 
    \d+ 
    \s{2,} 
    (.*) 
""" 

regex = re.compile(pattern, re.X) 

try: 
    with open(fileName) as inputFile: 
     # Loop over lines and extract variables of interest 
     for line in inputFile: 
      print(line) 
      match_obj = regex.match(line) 

      if match_obj: # pattern matched 
       name = match_obj.group(1) # group 1 is the first object 
       directory = match_obj.group(2) 
       print(name + "=>" + directory) 
      else: 
       print("Line not matched: " + line) 

     inputFile.close() 
except (OSError, IOError) as err: 
    raise IOError("%s: %s" % (fileName, err.strerror)) 

每次我運行代碼,我得到的打印(線)的錯誤,並在VS2015調試器只顯示新行。我是否在我的文件打開和讀取操作中丟失了某些內容?善良,這是我的第一個Python腳本!

該錯誤消息我回來就是YTH-'charmap」編解碼器無法編碼的字符‘在位置1 \ XFE’:字符映射爲

編輯(更新試行): 我接收到相同的錯誤消息,如果我運行命令行腳本:

File "RecuvaRenamer.py", line 21 in print(line) File "C:\Python34\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 1 character maps to

+0

什麼錯誤?到目前爲止,代碼沒有任何明顯的錯誤。 – jonrsharpe

+0

道歉,忘了添加錯誤: ÿþ'charmap'編解碼器無法在位置1編碼字符'\ xfe':字符映射到 Sraivyn

+1

也許這個問題可以幫助您http://stackoverflow.com/questions/ 14630288/unicodeencodeerror-charmap-codec -cant-encode-character-maps-to-undefined –

回答

0

好吧,沒關係。代碼沒有錯。輸入文件未用UTF-8編碼。將輸入轉換爲UTF-8格式並且文件「幾乎」解析正確。