最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python中文件的創(chuàng)建與寫入實(shí)戰(zhàn)代碼

 更新時(shí)間:2023年10月07日 10:40:57   作者:DevGeek  
這篇文章主要給大家介紹了關(guān)于python中文件的創(chuàng)建與寫入的相關(guān)資料,在Python中文件寫入提供了不同的模式和方法來滿足不同的需求,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下

1.利用內(nèi)置函數(shù)獲取文件對(duì)象

  • 功能:
    • 生成文件對(duì)象,進(jìn)行創(chuàng)建,讀寫操作
  • 用法:
    • open(path,mode)
  • 參數(shù)說明∶
    • path:文件路徑
    • mode :操作模式
  • 返回值:
    • 文件對(duì)象
  • 舉例:
    • f = open('d://a.txt' , ‘w')

2. 文件操作的模式之寫入:

  • 寫入模式(“w”):打開文件進(jìn)行寫入操作。如果文件已存在,則會(huì)覆蓋原有內(nèi)容;如果文件不存在,則會(huì)創(chuàng)建新文件。
  • 注意:在寫入模式下,如果文件已存在,原有內(nèi)容將被清空。

3. 文件對(duì)象的操作方法之寫入保存:

  • write(str):將字符串str寫入文件。它返回寫入的字符數(shù)。

    file.write("Hello, world!\n")
  • writelines(lines):將字符串列表lines中的每個(gè)字符串寫入文件。它不會(huì)在字符串之間添加換行符??梢酝ㄟ^在每個(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ù)獲取文件對(duì)象并進(jìn)行寫入保存操作:

# 打開文件并獲取文件對(duì)象
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"的文件,獲取了文件對(duì)象file。然后,我們使用文件對(duì)象的write方法寫入了單行文本和writelines方法寫入了多行文本。最后,我們調(diào)用了close方法關(guān)閉文件。

請(qǐng)確保在寫入完成后調(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 淺談python新式類和舊式類區(qū)別

    淺談python新式類和舊式類區(qū)別

    python的新式類是2.2版本引進(jìn)來的,我們可以將之前的類叫做經(jīng)典類或者舊式類。這篇文章主要介紹了淺談python新式類和舊式類區(qū)別,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-04-04
  • python類定義的講解

    python類定義的講解

    python是怎么定義類的,看了下面的文章大家就會(huì)了,不用多說,開始學(xué)習(xí)。
    2013-11-11
  • 解決tensorflow讀取本地MNITS_data失敗的原因

    解決tensorflow讀取本地MNITS_data失敗的原因

    這篇文章主要介紹了解決tensorflow讀取本地MNITS_data失敗的原因,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python中的賦值、淺拷貝、深拷貝介紹

    Python中的賦值、淺拷貝、深拷貝介紹

    這篇文章主要介紹了Python中的賦值、淺拷貝、深拷貝介紹,Python中也分為簡(jiǎn)單賦值、淺拷貝、深拷貝這幾種“拷貝”方式,需要的朋友可以參考下
    2015-03-03
  • Python類和對(duì)象基礎(chǔ)入門介紹

    Python類和對(duì)象基礎(chǔ)入門介紹

    Python 是一種面向?qū)ο蟮木幊陶Z言。Python 中的幾乎所有東西都是對(duì)象,擁有屬性和方法。類(Class)類似對(duì)象構(gòu)造函數(shù),或者是用于創(chuàng)建對(duì)象的藍(lán)圖
    2022-08-08
  • python TCP Socket的粘包和分包的處理詳解

    python TCP Socket的粘包和分包的處理詳解

    這篇文章主要介紹了python TCP Socket的粘包和分包的處理詳解,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-02-02
  • 解決django跨域的問題小結(jié)(Hbuilder X)

    解決django跨域的問題小結(jié)(Hbuilder X)

    使用Django開發(fā)時(shí),可能會(huì)遇到跨域問題,尤其是當(dāng)后端與HbuilderX開發(fā)的前端結(jié)合使用時(shí),解決此問題的關(guān)鍵步驟包括安裝django-cors-headers庫,并在Django的settings.py中進(jìn)行相應(yīng)配置,本文給大家介紹解決django跨域的問題小結(jié),感興趣的朋友一起看看吧
    2024-10-10
  • Python獲取DLL和EXE文件版本號(hào)的方法

    Python獲取DLL和EXE文件版本號(hào)的方法

    這篇文章主要介紹了Python獲取DLL和EXE文件版本號(hào)的方法,實(shí)例分析了Python獲取系統(tǒng)文件信息的技巧,需要的朋友可以參考下
    2015-03-03
  • 在python中pandas讀文件,有中文字符的方法

    在python中pandas讀文件,有中文字符的方法

    今天小編就為大家分享一篇在python中pandas讀文件,有中文字符的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • python實(shí)現(xiàn)樸素貝葉斯算法

    python實(shí)現(xiàn)樸素貝葉斯算法

    這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)樸素貝葉斯算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-11-11

最新評(píng)論

辽阳市| 麻阳| 延津县| 安徽省| 汾阳市| 行唐县| 内丘县| 新建县| 从江县| 县级市| 苍南县| 客服| 玉田县| 山丹县| 遂宁市| 夏邑县| 辽宁省| 丽水市| 宣汉县| 永福县| 沙河市| 都昌县| 绵阳市| 东至县| 曲阜市| 车险| 乌鲁木齐县| 大化| 甘德县| 榆树市| 曲松县| 英超| 湖北省| 汝城县| 图们市| 竹山县| 永善县| 黄大仙区| 五大连池市| 滨州市| 武汉市|