tgao@tgao-IdeaPad-U430p:~$ ls
Desktop Downloads Music Public Templates
Documents examples.desktop Pictures pythonPractice Videos
tgao@tgao-IdeaPad-U430p:~$ cd pythonPractice
tgao@tgao-IdeaPad-U430p:~/pythonPractice$ ls
cookbook_p150.py cookbook_p29.py cookbook_p4.py dw_test_dict.py
cookbook_p22.py cookbook_p30.py cookbook_p56.py helloworld.py
cookbook_p24.py cookbook_p335.py cookbook_p8.py regexdoc.py
cookbook_p27.py cookbook_p37.py cookbook_p9.py
tgao@tgao-IdeaPad-U430p:~/pythonPractice$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.path.exists('cookbook_p150.py')
True
>>> os.path.abspath('cookbook_p150.py')
'/home/tgao/pythonPractice/cookbook_p150.py'
>>> os.path.exists('/home/tgao/pythonPractice/cookbook_p150.py')
True
>>>
问题:判断是否存在某文件,如果存在,则告诉用户。否则写入数据
import os
if not os.path.exists('cookbook_p149.txt'):
with open('cookbook_p149.txt','w') as f:
f.write('hello\n')
else:
print('File already exists')