Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何同时处理UTF-8字符串以便打印和存储到文件中?_Python_Python 3.x_String_File_Utf 8 - Fatal编程技术网

Python 如何同时处理UTF-8字符串以便打印和存储到文件中?

Python 如何同时处理UTF-8字符串以便打印和存储到文件中?,python,python-3.x,string,file,utf-8,Python,Python 3.x,String,File,Utf 8,我有一段代码,可以读取特定目录中的文件。然后它在控制台上打印文件名,同时将它们写入日志文件。如果目录中的文件名中有一个Unicode字符的文件,脚本将因错误而停止。我知道如何打印文件名。但我不知道如何将文件名写入日志文件 这是我的代码(在Mac上,文件系统是UTF-8): 在这种情况下,错误是 b'/Volumes/USB/dir/testa\xcc\x88test.mp4' 回溯(最近一次呼叫最后一次): 文件“/temp/list dir.py中的文件”,第15行,在 logfile.wri

我有一段代码,可以读取特定目录中的文件。然后它在控制台上打印文件名,同时将它们写入日志文件。如果目录中的文件名中有一个Unicode字符的文件,脚本将因错误而停止。我知道如何打印文件名。但我不知道如何将文件名写入日志文件

这是我的代码(在Mac上,文件系统是UTF-8):

在这种情况下,错误是

b'/Volumes/USB/dir/testa\xcc\x88test.mp4'
回溯(最近一次呼叫最后一次):
文件“/temp/list dir.py中的文件”,第15行,在
logfile.write('读取文件:'+file+'“\n')
UnicodeEncodeError:“ascii”编解码器无法对位置46中的字符“\u0308”进行编码:序号不在范围内(128)
当我把最后一行改为

    logfile.write('Reading file: "'+file2+'"\n')
那么错误是

回溯(最近一次呼叫最后一次):
文件“/temp/list dir.py中的文件”,第15行,在
logfile.write('读取文件:'+file2+'“\n')
TypeError:必须是str,而不是bytes
我的编码/解码有问题。但是什么呢

编辑

感谢下面@lenz的评论,我现在可以写入日志文件了

然后我在代码中添加了一行新行

size = os.path.getsize(file)
现在我得到一个新的错误:

Traceback (most recent call last):
  File "/temp/list-files-in-dir.py", line 16, in <module>
    size = os.path.getsize(file)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/genericpath.py", line 50, in getsize
    return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: '/Volumes/USB/dir/testa\xcc\x88test.mp4'

Python3字符串是默认的Unicode。使用所需的编码打开文件,不要手动编码。这将解决您稍后遇到的
os.path.getsize
问题,因为它还需要Unicode字符串

import os

rootdir = '/Volumes/USB/dir/'

# "with" will close the file when its block is exited.
# Specify the encoding when opening the file.
with open('temp.txt','w',encoding='utf8') as logfile:
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:                                                  
            file = os.path.join(subdir, file)  
            print(file)
            logfile.write('Reading file: "'+file+'"\n')

我发现,只有在使用MagicPython扩展从Visual Studio代码编辑器中运行脚本时,才会出现此问题。当我从一个普通的shell运行这段代码时,一切都正常工作,UTF-8处理也正确完成

尝试使用:logfile=open('temp.txt','a','utf-8')@gkivanov更改日志文件的open行。第三个位置参数是
缓冲
,因此需要将编码指定为关键字参数:
logfile=open('temp.txt','a',encoding='utf8')
。为什么要执行
编码
?在Python3中,
print
write
都应该透明地处理Unicode(尽管如果您使用的是旧的或残废的平台,如Windows,您可能需要修改输出编码设置)。@lenz谢谢。这有助于解决一个错误,但现在我有了一个新的错误。
try:
  size = os.path.getsize(file)
except:
  size = 0
import os

rootdir = '/Volumes/USB/dir/'

# "with" will close the file when its block is exited.
# Specify the encoding when opening the file.
with open('temp.txt','w',encoding='utf8') as logfile:
    for subdir, dirs, files in os.walk(rootdir):
        for file in files:                                                  
            file = os.path.join(subdir, file)  
            print(file)
            logfile.write('Reading file: "'+file+'"\n')