欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python3 文件

程序员文章站 2022-07-05 16:11:30
...

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在写入完文件后,会自动关闭该文件