python-文件的创建与写入

这篇具有很好参考价值的文章主要介绍了python-文件的创建与写入。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.利用内置函数获取文件对象

  • 功能:
    • 生成文件对象,进行创建,读写操作
  • 用法:
    • open(path,mode)
  • 参数说明∶
    • path:文件路径
    • mode :操作模式
  • 返回值:
    • 文件对象
  • 举例:
    • f = open('d://a.txt' , ‘w')

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

  • 写入模式(“w”):打开文件进行写入操作。如果文件已存在,则会覆盖原有内容;如果文件不存在,则会创建新文件。
  • 注意:在写入模式下,如果文件已存在,原有内容将被清空。

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,视打开的原文件编码格式而定

实战

在这里插入代码片# 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已经存在,不可创建' % 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文章来源地址https://www.toymoban.com/news/detail-675105.html

# 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-文件的创建与写入的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • python读取txt文件内容,写入csv文件中去。

    txt文件中的内容大概是这样的: 2.在图3中,当开关断开时,R1、R2_______(串联/并联),当开关闭合时, 被短路。开关由断开转为闭合时,总电阻 ,总电流_______,通过R2的电流_______(变大/变小/不变)。 3.如图3,当开关闭合时,R2两端电压为3V,若R2=10Ω,则电流为_______。断开

    2023年04月08日
    浏览(48)
  • C 语言文件处理全攻略:创建、写入、追加操作解析

    在 C 语言中,您可以通过声明类型为 FILE 的指针,并使用 fopen() 函数来创建、打开、读取和写入文件: FILE 基本上是一个数据类型,我们需要创建一个指针变量来使用它 ( fptr )。现在,这行代码并不重要。它只是在处理文件时需要的东西。 要实际打开文件,请使用 fopen() 函数

    2024年02月03日
    浏览(36)
  • 6.6:Python如何在写入文件时覆盖原有的内容?

    Python作为一门高级编程语言,其功能十分强大,同时也是一门非常流行的编程语言。在Python编程中,文件读写操作是非常常见的任务。有时候,我们需要覆盖原有的文件内容,例如在写日志文件时,需要每次写入新的内容,覆盖掉原有的内容。为了满足这个需求,Python提供了

    2024年02月07日
    浏览(31)
  • python-文件的创建与写入

    功能: 生成文件对象,进行创建,读写操作 用法: open(path,mode) 参数说明∶ path:文件路径 mode :操作模式 返回值: 文件对象 举例: f = open(\\\'d://a.txt\\\' , ‘w\\\') 写入模式(“w”):打开文件进行写入操作。如果文件已存在,则会覆盖原有内容;如果文件不存在,则会创建新文件。 注意

    2024年02月11日
    浏览(26)
  • [excel与dict] python 读取excel内容并放入字典、将字典内容写入 excel文件

    一 读取excel内容、并放入字典 1 读取excel文件 2 读取value,舍弃行号 3 读取为字典 一 读取excel内容、并放入字典(完整代码) 二、将字典内容写入 excel文件 1 假设已有字典内容为: 即student列表里有4个字典, 第一个字典里面有3对key-value \\\"num\\\": 1, \\\"name\\\": \\\"cod1\\\", \\\"wfm\\\": 0.1 2 导入Workb

    2024年02月04日
    浏览(36)
  • Python 文件处理指南:打开、读取、写入、追加、创建和删除文件

    文件处理是任何Web应用程序的重要部分。Python有多个用于创建、读取、更新和删除文件的函数。 在Python中处理文件的关键函数是open()函数。open()函数接受两个参数:文件名和模式。 有四种不同的方法(模式)可以打开文件: \\\"r\\\" - 读取 - 默认值。打开一个文件以进行读取,如

    2024年02月05日
    浏览(52)
  • C# 创建Excel并写入内容

            在许多应用程序中,需要将数据导出为Excel表格,以便用户可以轻松地查看和分析数据。在本文中,我们将讨论如何使用C#创建Excel表格,并将数据写入该表格。 添加引用 在C#中创建Excel表格,需要使用Microsoft.Office.Interop.Excel命名空间中的类。打开Visual Studio,选择

    2024年02月11日
    浏览(31)
  • C++ 写入txt文件内容并追加内容

    咨询通义千问的“C++ 写入txt文件内容并追加内容”: 可以使用ofstream类来写入txt文件内容。若想追加内容,可以使用ios::app标志来创建输出流对象,然后在写入时将其设置为ios::app。以下是一个示例代码: 在这个例子中,我们创建了一个名为“example.txt”的输出流对象,并将

    2024年02月11日
    浏览(35)
  • Linux向文件中写入内容

    1.覆盖写入 2.追加写入 3.窗口输出指定内容

    2024年02月09日
    浏览(30)
  • 使用BeanShell写入内容到文件【JMeter】

    ​ 在我们日常工作中,可能会遇到需要将请求返回的数据写入到文件中。在我们使用JMeter进行性能测试时,就经常能够遇到这种情况。要想达到这种目的,我们一般采取BeanShell后置处理器来将内容写入到文件。 ​ 在目前大多数的性能测试中,都是以JSON形式返回结果。因此我

    2024年02月11日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包