python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python文件创建与写入

python中文件的创建与写入实战代码

作者:DevGeek

这篇文章主要给大家介绍了关于python中文件的创建与写入的相关资料,在Python中文件写入提供了不同的模式和方法来满足不同的需求,文中通过代码介绍的非常详细,需要的朋友可以参考下

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

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

3. 文件对象的操作方法之写入保存:

以下是一个示例代码,演示如何使用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

# 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中文件的创建与写入的文章就介绍到这了,更多相关python文件创建与写入内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文