首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python-os-04-新建文件夹及文本文件

系统:Windows 7 语言版本:Anaconda3-4.3.0.1-Windows-x86_64 编辑器:pycharm-community-2016.3.2 Python:3.6.0

  • 这个系列讲讲os模块常用功能
  • 本文介绍:新建文件夹及文本文件

Part 1:代码

代码语言:javascript
复制
import os
current_dir = os.path.dirname(os.path.abspath(__file__))# 创建文件夹folder_name = "HelloWorld"folder_address = os.path.join(current_dir, folder_name)
if not os.path.exists(folder_address):    os.mkdir(folder_address)
# 创建文件txt_file_name = "HelloWorld.txt"txt_file_address = os.path.join(current_dir, txt_file_name)
# 检查文件是否存在,存在则删除if os.path.exists(txt_file_address):    os.remove(txt_file_address)
f = open(txt_file_address, 'w')f.write("HelloWorld")f.close()

代码截图

未执行代码前

执行代码后

Part 2:部分代码解读

  1. os.mkdir(folder_address),创建新文件夹
  2. f = open(txt_file_address, 'w'),打开一个文件,并进入写入模式,若该文件不存在,则创建
  3. f.write("HelloWorld")向文件中写入HelloWorld信息。 若想一行一行写入,需要在每一行内容间增加f.write("\n") f = open(txt_file_address, 'w') f.write("HelloWorld") f.write("\n") f.write("HelloWorld") f.write("\n") f.write("HelloWorld") f.write("\n") f.write("HelloWorld") f.close() 执行结果
  1. 若不增加f.write("\n"),如下 f = open(txt_file_address, 'w') f.write("HelloWorld") f.write("HelloWorld") f.write("HelloWorld") f.write("HelloWorld") f.close() 结果如下

本文为原创作品,欢迎分享朋友圈

下一篇
举报
领券