开发者

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

目录
  • 1.利用内置函数获取文件对象
  • 2. 文件操作的模式之写入:
  • 3. 文件对象的操作方法之写入保存:
  • 实战
  • 总结 

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_packawww.devze.comge(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_returnandroid
    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=Tpythonrue):
        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/28android
# @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:python%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文件创建与写入内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜