Python3 文件

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

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

>>> open('C:\Users\fengx\Desktop\sharing\search_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在写入完文件后,会自动关闭该文件

posted @ 2018-12-28 09:57  月亮上的石头  阅读(74)  评论(0)    收藏  举报