python中文件的創(chuàng)建與寫入實(shí)戰(zhàn)代碼
1.利用內(nèi)置函數(shù)獲取文件對象
- 功能:
- 生成文件對象,進(jìn)行創(chuàng)建,讀寫操作
- 用法:
open(path,mode)
- 參數(shù)說明∶
- path:文件路徑
- mode :操作模式
- 返回值:
- 文件對象
- 舉例:
f = open('d://a.txt' , ‘w')
2. 文件操作的模式之寫入:
- 寫入模式(“w”):打開文件進(jìn)行寫入操作。如果文件已存在,則會覆蓋原有內(nèi)容;如果文件不存在,則會創(chuàng)建新文件。
- 注意:在寫入模式下,如果文件已存在,原有內(nèi)容將被清空。
3. 文件對象的操作方法之寫入保存:
write(str)
:將字符串str
寫入文件。它返回寫入的字符數(shù)。file.write("Hello, world!\n")
writelines(lines)
:將字符串列表lines
中的每個(gè)字符串寫入文件。它不會在字符串之間添加換行符。可以通過在每個(gè)字符串末尾添加換行符來實(shí)現(xiàn)換行。lines = ["This is line 1\n", "This is line 2\n", "This is line 3\n"] file.writelines(lines)
close()
:關(guān)閉文件,釋放文件資源。在寫入完成后,應(yīng)該調(diào)用該方法關(guān)閉文件。file.close()
以下是一個(gè)示例代碼,演示如何使用open
函數(shù)獲取文件對象并進(jìn)行寫入保存操作:
# 打開文件并獲取文件對象 file = open("example.txt", "w") # 寫入單行文本 file.write("Hello, world!\n") # 寫入多行文本 lines = ["This is line 1\n", "This is line 2\n", "This is line 3\n"] file.writelines(lines) # 關(guān)閉文件 file.close()
在上述示例中,我們首先使用open
函數(shù)以寫入模式打開名為"example.txt"的文件,獲取了文件對象file
。然后,我們使用文件對象的write
方法寫入了單行文本和writelines
方法寫入了多行文本。最后,我們調(diào)用了close
方法關(guān)閉文件。
請確保在寫入完成后調(diào)用close
方法來關(guān)閉文件,以釋放文件資源和確保寫入的數(shù)據(jù)被保存。
操作完成后,必須使用close方法!
避坑指南:
#當(dāng)打開的文件中有中文的時(shí)候,需要設(shè)置打開的編碼格式為utf-8或gbk,視打開的原文件編碼格式而定
實(shí)戰(zhàn)
在這里插入代碼片# coding:utf-8 # @Author: DX # @Time: 2023/5/29 # @File: package_open.py import os def create_package(path): if os.path.exists(path): raise Exception('%s已經(jīng)存在,不可創(chuàng)建' % path) os.makedirs(path) init_path = os.path.join(path, '__init__.py') f = open(init_path, 'w', encoding='utf-8') f.write('# coding: utf-8\n') f.close() class Open(object): def __init__(self, path, mode='w', is_return=True): self.path = path self.mode = mode self.is_return = is_return def write(self, message): f = open(self.path, mode=self.mode, encoding='utf-8') try: if self.is_return and message.endswith('\n'): message = '%s\n' % message f.write(message) except Exception as e: print(e) finally: f.close() def read(self, is_strip=True): result = [] with open(self.path, mode=self.mode, encoding='utf-8') as f: data = f.readlines() for line in data: if is_strip: temp = line.strip() if temp != '': result.append(temp) else: if line != '': result.append(line) return result if __name__ == '__main__': current_path = os.getcwd() # path = os.path.join(current_path, 'test2') # create_package(path) open_path = os.path.join(current_path, 'b.txt') o = open('package_datetime.py', mode='r', encoding='utf-8') # o = os.write('你好~') data1 = o.read() print(data1)
輸出結(jié)果(遍歷了package_datetime.py中的內(nèi)容):
# coding:utf-8 # Time: 2023/5/28 # @Author: Dx # @File:package_datetime.py from datetime import datetime from datetime import timedelta now = datetime.now() print(now, type(now)) now_str = now.strftime('%Y-%m-%d %H:%M:%S') print(now_str, type(now_str)) now_obj = datetime.strptime(now_str, '%Y-%m-%d %H:%M:%S') print(now_obj, type(now_obj)) print('===========================================') three_days = timedelta(days=3) # 這個(gè)時(shí)間間隔是三天,可以代表三天前或三天后的范圍 after_three_days = three_days + now print(after_three_days) after_three_days_str = after_three_days.strftime('%Y/%m/%d %H:%M:%S:%f') print(after_three_days_str, type(after_three_days_str)) after_three_days_obj = datetime.strptime(after_three_days_str, '%Y/%m/%d %H:%M:%S:%f') print(after_three_days_obj, type(after_three_days_obj)) print('===========================================') before_three_days = now - three_days print(before_three_days) before_three_days_str = before_three_days.strftime('%Y/%m/%d %H:%M:%S:%f') print(before_three_days_str, type(before_three_days_str), '=================') before_three_days_obj = datetime.strptime(before_three_days_str, '%Y/%m/%d %H:%M:%S:%f') print(before_three_days_obj, type(before_three_days_obj)) print('===========================================') one_hour = timedelta(hours=1) after_one_hour = now + one_hour after_one_hour_str = after_one_hour.strftime('%H:%M:%S') print(after_one_hour_str) after_one_hour_obj = datetime.strptime(after_one_hour_str, '%H:%M:%S') print(after_one_hour_obj, type(after_one_hour_obj)) # default_str = '2023 5 28 abc' # default_obj = datetime.strptime(default_str, '%Y %m %d') 進(jìn)程已結(jié)束,退出代碼0
package_datetime.py
# coding:utf-8 # Time: 2023/5/28 # @Author: Dx # @File:package_datetime.py from datetime import datetime from datetime import timedelta now = datetime.now() print(now, type(now)) now_str = now.strftime('%Y-%m-%d %H:%M:%S') print(now_str, type(now_str)) now_obj = datetime.strptime(now_str, '%Y-%m-%d %H:%M:%S') print(now_obj, type(now_obj)) print('===========================================') three_days = timedelta(days=3) # 這個(gè)時(shí)間間隔是三天,可以代表三天前或三天后的范圍 after_three_days = three_days + now print(after_three_days) after_three_days_str = after_three_days.strftime('%Y/%m/%d %H:%M:%S:%f') print(after_three_days_str, type(after_three_days_str)) after_three_days_obj = datetime.strptime(after_three_days_str, '%Y/%m/%d %H:%M:%S:%f') print(after_three_days_obj, type(after_three_days_obj)) print('===========================================') before_three_days = now - three_days print(before_three_days) before_three_days_str = before_three_days.strftime('%Y/%m/%d %H:%M:%S:%f') print(before_three_days_str, type(before_three_days_str), '=================') before_three_days_obj = datetime.strptime(before_three_days_str, '%Y/%m/%d %H:%M:%S:%f') print(before_three_days_obj, type(before_three_days_obj)) print('===========================================') one_hour = timedelta(hours=1) after_one_hour = now + one_hour after_one_hour_str = after_one_hour.strftime('%H:%M:%S') print(after_one_hour_str) after_one_hour_obj = datetime.strptime(after_one_hour_str, '%H:%M:%S') print(after_one_hour_obj, type(after_one_hour_obj)) # default_str = '2023 5 28 abc' # default_obj = datetime.strptime(default_str, '%Y %m %d')
總結(jié)
到此這篇關(guān)于python中文件的創(chuàng)建與寫入的文章就介紹到這了,更多相關(guān)python文件創(chuàng)建與寫入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于C++和python實(shí)現(xiàn)阿姆斯特朗數(shù)字查找的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12pandas read_excel()和to_excel()函數(shù)解析
這篇文章主要介紹了pandas read_excel()和to_excel()函數(shù)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09python之pygame模塊實(shí)現(xiàn)飛機(jī)大戰(zhàn)完整代碼
這篇文章主要為大家詳細(xì)介紹了python之pygame模塊實(shí)現(xiàn)飛機(jī)大戰(zhàn)完整代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11Python中處理unchecked未捕獲異常實(shí)例
這篇文章主要介紹了Python中處理unchecked未捕獲異常實(shí)例,本文講解使用回調(diào)或者是鉤子來處理unchecked異常,需要的朋友可以參考下2015-01-01詳解使用python的logging模塊在stdout輸出的兩種方法
這篇文章主要介紹了詳解使用python的logging模塊在stdout輸出的相關(guān)資料,需要的朋友可以參考下2017-05-05使用Python+Matplotlib制作時(shí)序動態(tài)圖
時(shí)序圖是一個(gè)二維圖,橫軸表示對象,縱軸表示時(shí)間,消息在各對象之間橫向傳遞,依照時(shí)間順序縱向排列,可以直觀的描述并發(fā)進(jìn)程,所以本文就使用Python和Matplotlib制作一個(gè)簡單的時(shí)許動態(tài)圖,感興趣的跟著小編一起來看看吧2023-07-07pandas 如何保存數(shù)據(jù)到excel,csv
這篇文章主要介紹了pandas 如何保存數(shù)據(jù)到excel,csv的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07幫你快速上手Jenkins并實(shí)現(xiàn)自動化部署
在未學(xué)習(xí)Jenkins之前,只是對Jenkins有一個(gè)比較模糊的理解,即Jenkins是一個(gè)自動化構(gòu)建項(xiàng)目發(fā)布的工具,可以實(shí)現(xiàn)代碼->github或者gitlab庫->jenkins自動部署->訪問的整體的過程,而無需人為重新打包,今天就帶大家詳細(xì)了解一下,幫你快速上手Jenkins,需要的朋友可以參考下2021-06-06Python 實(shí)現(xiàn)一個(gè)顏色色值轉(zhuǎn)換的小工具
這篇文章主要介紹了Python 實(shí)現(xiàn)一個(gè)顏色色值轉(zhuǎn)換的小工具的相關(guān)資料,需要的朋友可以參考下2016-12-12