如何用python创建文件_如何使用Python创建新的文本文件

我正在python中练习.txt文件的管理.我一直在阅读它,发现如果我尝试打开一个不存在的文件,它将在程序执行的同一目录上创建它.问题是,当我尝试打开它时,我收到此错误:

IOError: [Errno 2] No such file or directory:

‘C:\Users\myusername\PycharmProjects\Tests\copy.txt’.

我甚至尝试在错误中看到指定路径.

import os

THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))

my_file = os.path.join(THIS_FOLDER, 'copy.txt')

解决方法:

看起来你在调用open时忘记了mode参数,试试w:

file = open("copy.txt", "w")

file.write("Your text goes here")

file.close()

默认值为r,如果文件不存在则将失败

'r' open for reading (default)

'w' open for writing, truncating the file first

其他有趣的选择是

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of the file if it exists

– 编辑 –

正如chepner在下面的评论中所述,更好的做法是使用withstatement(它保证文件将被关闭)

with open("copy.txt", "w") as file:

file.write("Your text goes here")

标签:python,python-2-7

来源: https://codeday.me/bug/20191007/1868977.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值