Python3 文件

f=open('C:\Users\fengx\Desktop\sharing\test.txt')

如果打开文件的格式不匹配,可能会报如下错:

>>> open('C:UsersfengxDesktopsharingsearch_words_in_dir.py')
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape

  

不要直接使用open(xxx),会导致无法关闭该文件

最好用如下方式打开文件,并且指定打开文件的格式:

with open('C:/Users/fengx//Desktop/sharing/test.txt', 'w') as f:
    f.write('Hello, world!')

python在写入完文件后,会自动关闭该文件

原文地址:https://www.cnblogs.com/vigossr/p/10188804.html