【问题标题】:UnicodeDecode issue -- writing to a SAS program fileUnicodeDecode 问题——写入 SAS 程序文件
【发布时间】:2014-01-29 22:13:52
【问题描述】:

我收到了大量的 sas 文件,它们都需要更改其文件路径。

我为该任务编写的代码如下:

import glob
import os
import sys 

os.chdir(r"C:\path\subdir")
glob.glob('*.sas')
import os
fileLIST=[]
for dirname, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        fileLIST.append(os.path.join(dirname, filename))
print fileLIST

import re

for fileITEM in set(fileLIST):
    dataFN=r"//path/subdir/{0}".format(fileITEM)
    dataFH=open(dataFN, 'r+')

    for row in dataFH:
    print row
        if re.findall('\.\.\.', str(row)) != []:
            dataSTR=re.sub('\.\.\.', "//newpath/newsubdir", row)
        print >> dataFH, dataSTR.encode('utf-8')
    else:
        print >> dataFH, row.encode('utf-8')
dataFH.close()

我有两个问题:首先,我的代码似乎无法识别三个连续的句点,即使用反斜杠分隔也是如此。其次,我收到一个错误“UnicodeDecodeError: 'ascii' codec can't decode byte...'

SAS 程序文件 (.sas) 是否可能不是 utf-8?如果是这样,修复是否像知道他们使用什么文件编码一样简单?

完整的回溯如下:

Traceback (most recent call last):
  File "stringsubnew.py", line 26, in <module>
    print >> dataFH, row.encode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0x83 in position 671: ordinal not in range(128)

提前致谢

【问题讨论】:

  • 问题在于 ASCII 编解码器试图用非 ASCII 字节解码某些东西,所以不是 UTF-8 的文件不是你的问题。请包含完整的回溯,或至少包含哪一行生成异常。
  • SAS 程序文件可以是 UTF-8 或其他格式(最常见的是 wlatin1),具体取决于创建/保存它们的会话编码。
  • Wooble -- 刚刚将回溯添加到原始帖子。

标签: python encoding sas


【解决方案1】:

问题在于阅读而不是写作。您必须知道正在读取的源文件中的编码是什么,并对其进行适当的解码。

假设源文件包含用 iso-8859-1 编码的数据

使用 str.decode() 阅读时可以这样做

my_row = row.decode('iso-8859-1')

或者您可以使用编解码器打开文件,为您处理。

import codecs

dataFH = codecs.open(dataFN, 'r+', 'iso-8859-1')

可以在http://nedbatchelder.com/text/unipain.html找到关于此的精彩讨论

【讨论】:

  • 感谢提示 从我的代码中删除 'encode('utf-8') 后,我收到以下错误:Traceback (most recent call last): File "unicodeattempt.py", line 25, in &lt;module&gt; print &gt;&gt; dataFH, row IOError: [Errno 0] Error
  • 你试过解码和编码,你都需要。解码数据读取(输入),编码输出数据(输出)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多