python新建记事本_python怎么创建文本文件

python创建文本文件的方法:首先利用open()函数以只写模式打开一个文件,如果该文件不存在则创建;然后利用write()函数向该文件中写入指定字符串即可。

0f314ac0d0f70866b97abb6f6c9d0802.png

python open() 函数以指定模式打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。

(推荐教程:Python入门教程)

w 模式表示打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。

write() 方法用于向文件中写入指定字符串。在文件关闭前或缓冲区刷新前,字符串内容存储在缓冲区中,这时你在文件中是看不到写入的内容的。

实现代码:#!/usr/bin/python

# -*- coding:utf-8 -*-

file = open('C:/Users/Administrator/Desktop/a/b.txt','w')

file.write('你好,\n  世界。')

结果:

0b8d131032580e67d1db544e0e1492d9.png

打开这个文本可以看到内容成功写入。

6c473fd81f91685b75df123cdcbe4c3c.png

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Python的Tkinter模块来创建一个简单的记事本程序。以下是一个基本的代码示例: ```python from tkinter import * from tkinter.filedialog import asksaveasfilename, askopenfilename current_file = None def new_file(): global current_file text.delete(1.0, END) current_file = None def open_file(): global current_file file_path = askopenfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]) if not file_path: return text.delete(1.0, END) with open(file_path, "r") as file: text.insert(INSERT, file.read()) current_file = file_path def save_file(): global current_file if not current_file: current_file = asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]) if not current_file: return with open(current_file, "w") as file: file.write(text.get(1.0, END)) root = Tk() root.title("Notepad") text = Text(root, wrap=WORD) text.pack(expand=YES, fill=BOTH) menu = Menu(root) root.config(menu=menu) file_menu = Menu(menu) menu.add_cascade(label="File", menu=file_menu) file_menu.add_command(label="New", command=new_file) file_menu.add_command(label="Open", command=open_file) file_menu.add_command(label="Save", command=save_file) root.mainloop() ``` 上面的代码创建了一个基本的窗口和一个文本框,以及“新建”、“打开”和“保存”菜单选项。点击“新建”会清空文本框并将当前文件设置为None,点击“打开”会弹出一个文件选择框,选择一个文本文件并将其内容显示在文本框中,同时将当前文件设置为所选文件的路径,点击“保存”会将文本框中的内容保存到当前文件中,如果当前文件为空,则会弹出一个保存文件框来选择保存文件的路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值