python中newfile是干嘛用的_Python基础介绍 | File I\O 读写文件
如何用Python讀寫文件呢?我們有許多種辦法,包括使用Pandas或者使用os相關的工具,我們來看一下:
首先,得明白文件路徑的事情:
import os
current_file = os.path.realpath('file_io.ipynb')
print('current file: {}'.format(current_file))
# Note: in .py files you can get the path of current file by __file__
current_dir = os.path.dirname(current_file)
print('current directory: {}'.format(current_dir))
# Note: in .py files you can get the dir of current file by os.path.dirname(__file__)
data_dir = os.path.join(current_dir, 'data')
print('data directory: {}'.format(data_dir))
當然也可以使用getcwd()這個函數獲得當前路徑
查看某路徑是否存在
print('exists: {}'.format(os.path.exists(data_dir)))
print('is file: {}'.format(os.path.isfile(data_dir)))
print('is directory: {}'.format(os.path.isdir(data_dir)))
讀取文件
file_path = os.path.join(data_dir, 'simple_file.txt')
with open(file_path, 'r') as simple_file:
for line in simple_file:
print(line.strip())
with語句用于獲取上下文管理器,該上下文管理器將用作with內部命令的執行上下文。上下文管理器確保在退出上下文時執行某些操作。
在本例中,上下文管理器保證在退出上下文時將隱式調用simple_file.close()。這是一種簡化開發人員工作的方法:您不必記住顯式地關閉已打開的文件,也不必擔心在打開文件時發生異常。未關閉的文件可能是資源泄漏的來源。因此,最好與open()結構一起使用,總是與文件I/O一起使用。
舉個不是用with管理的例子:
file_path = os.path.join(data_dir, 'simple_file.txt')
# THIS IS NOT THE PREFERRED WAY
simple_file = open(file_path, 'r')
for line in simple_file:
print(line.strip())
simple_file.close() # This has to be called explicitly
寫入文件:如果之前沒有這個文件的話,容易生成
new_file_path = os.path.join(data_dir, 'new_file.txt')
with open(new_file_path, 'w') as my_file:
my_file.write('This is my first file that I wrote with Python.')
然后,去看看有沒有new_file.txt這個文件,有的話可以用以下文件進行刪除
if os.path.exists(new_file_path): # make sure it's there
os.remove(new_file_path)
PS: 我在日常中對數據進行操作,一般會使用Pandas進行,尤其是對CSV這類格式的操作。
參考資料:
總結
以上是生活随笔為你收集整理的python中newfile是干嘛用的_Python基础介绍 | File I\O 读写文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python仪表指针识别_一种指针式仪表
- 下一篇: cad计算总长度插件_超实用的CAD插件