日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中newfile是干嘛用的_Python基础介绍 | File I\O 读写文件

發布時間:2024/7/23 python 81 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 读写文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。