【python】文件讀取和判斷

Table of Contents

1 判斷文件是否存在

2 寫入文件

3 讀取文件

4 json讀取和寫入


 

1 判斷文件是否存在

os.path.exists()

當文件或文件夾存在時返回true。

os.path.is(file)

是文件的時候返回true,是文件夾時候返回false。

>>> import os
>>> link = r'C:\test'
>>> os.path.exists(link)
True
>>> os.path.isfile(link)
False
>>> a=os.path.join(link, 'a.txt')
>>> a
'C:\\test\\a.txt'
>>> os.path.isfile(a)
True
>>> 

 

2 寫入文件

# 方法一。不需要手動close文件
with open("test.txt","w") as file:
    file.write("hello")


# 方法二。必須手動使用file.close()
file = open("test.txt","w")
file.write("hello")
file.close()

link:https://blog.csdn.net/suhuanyyy/article/details/88933655

 

3 讀取文件

https://blog.csdn.net/weixin_41656968/article/details/80904491

https://blog.csdn.net/qq_37076942/article/details/91348839

 

4 json讀取和寫入

注意,json中只能使用雙引號,不能有單引號,否則會報錯。

# 讀取
with open(file, 'r', encoding='utf-8') as json_file:
     json_data = json.load(json_file)

# 寫入
with open(signal_file, 'w') as file:
     json_data = {"key": "value"}
     file.write(json.dumps(json_data))

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章