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

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

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

1.利用內置函數獲取文件對象

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

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

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

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

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

    file.write("Hello, world!\n")
  • writelines(lines):將字符串列表lines中的每個字符串寫入文件。它不會在字符串之間添加換行符??梢酝ㄟ^在每個字符串末尾添加換行符來實現換行。

    lines = ["This is line 1\n", "This is line 2\n", "This is line 3\n"]
    file.writelines(lines)
  • close():關閉文件,釋放文件資源。在寫入完成后,應該調用該方法關閉文件。

    file.close()

以下是一個示例代碼,演示如何使用open函數獲取文件對象并進行寫入保存操作:

# 打開文件并獲取文件對象
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)
# 關閉文件
file.close()

在上述示例中,我們首先使用open函數以寫入模式打開名為"example.txt"的文件,獲取了文件對象file。然后,我們使用文件對象的write方法寫入了單行文本和writelines方法寫入了多行文本。最后,我們調用了close方法關閉文件。

請確保在寫入完成后調用close方法來關閉文件,以釋放文件資源和確保寫入的數據被保存。

操作完成后,必須使用close方法!
避坑指南:
#當打開的文件中有中文的時候,需要設置打開的編碼格式為utf-8或gbk,視打開的原文件編碼格式而定

實戰(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已經存在,不可創(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)

輸出結果(遍歷了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)  # 這個時間間隔是三天,可以代表三天前或三天后的范圍
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')
進程已結束,退出代碼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)  # 這個時間間隔是三天,可以代表三天前或三天后的范圍
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')

總結 

到此這篇關于python中文件的創(chuàng)建與寫入的文章就介紹到這了,更多相關python文件創(chuàng)建與寫入內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

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

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

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

    python類定義的講解

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

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

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

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

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

    Python類和對象基礎入門介紹

    Python 是一種面向對象的編程語言。Python 中的幾乎所有東西都是對象,擁有屬性和方法。類(Class)類似對象構造函數,或者是用于創(chuàng)建對象的藍圖
    2022-08-08
  • python TCP Socket的粘包和分包的處理詳解

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

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

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

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

    Python獲取DLL和EXE文件版本號的方法

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

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

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

    python實現樸素貝葉斯算法

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

最新評論

永州市| 揭西县| 安阳县| 汝州市| 辽中县| 遵化市| 瑞金市| 瑞金市| 中宁县| 安平县| 乐清市| 石棉县| 宝应县| 醴陵市| 无极县| 徐水县| 卫辉市| 榆林市| 松桃| 随州市| 昂仁县| 宁河县| 高安市| 景宁| 商丘市| 乐业县| 邳州市| 方山县| 古丈县| 安国市| 浮梁县| 盖州市| 咸阳市| 荔波县| 曲阜市| 呼伦贝尔市| 海伦市| 永春县| 同仁县| 哈尔滨市| 永登县|