如何使用 Python 创建一个新的文本文件 [英] How to create a new text file using Python

查看:92
本文介绍了如何使用 Python 创建一个新的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm practicing the management of .txt files in python. I've been reading about it and found that if I try to open a file that doesn't exists yet it will create it on the same directory from where the program is being executed. The problem comes that when I try to open it, I get this error:

IOError: [Errno 2] 没有这样的文件或目录:'C:\Users\myusername\PycharmProjects\Tests\copy.txt'.

IOError: [Errno 2] No such file or directory: 'C:\Users\myusername\PycharmProjects\Tests\copy.txt'.

我什至尝试指定一个路径,正如您在错误中看到的那样.

I even tried specifying a path as you can see in the error.

import os
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'copy.txt')

推荐答案

貌似你在调用open时忘记了mode参数,试试w:

Looks like you forgot the mode parameter when calling open, try w:

file = open("copy.txt", "w") 
file.write("Your text goes here") 
file.close() 

默认值为r,如果文件不存在就会失败

The default value is r and will fail if the file does not exist

'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

有关 Python2.7Python3.6

-- 编辑 --

正如 chepner 在下面的评论中所说,最好使用 with 语句来完成它(它保证文件将被关闭)

As stated by chepner in the comment below, it is better practice to do it with a withstatement (it guarantees that the file will be closed)

with open("copy.txt", "w") as file:
    file.write("Your text goes here")

这篇关于如何使用 Python 创建一个新的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆