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 1n", "This is line 2n", "This is line 3n"]
    file.writelines(lines)
    
  • close():关闭文件,释放文件资源。在写入完成后,应该调用该方法关闭文件。

    file.close()
    

以下是一个示例代码,演示如何使用open函数获取文件对象并进行写入保存操作:

# 打开文件并获取文件对象
file = open("example.txt", "w")

# 写入单行文本
file.write("Hello, world!n")

# 写入多行文本
lines = ["This is line 1n", "This is line 2n", "This is line 3n"]
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-8n')
    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 = '%sn' % 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')

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>