系统:Windows 7 语言版本:Anaconda3-4.3.0.1-Windows-x86_64 编辑器:pycharm-community-2016.3.2 Python:3.6.0
Part 1:代码
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:部分代码解读
os.mkdir(folder_address)
,创建新文件夹f = open(txt_file_address, 'w')
,打开一个文件,并进入写入模式,若该文件不存在,则创建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()
执行结果f.write("\n")
,如下
f = open(txt_file_address, 'w') f.write("HelloWorld") f.write("HelloWorld") f.write("HelloWorld") f.write("HelloWorld") f.close()
结果如下
本文为原创作品,欢迎分享朋友圈