简体   繁体   English

如何在 python 中创建一个 new.txt 文件

[英]How to create a new .txt file in python

I am trying to create a new.txt file in python by the following method if the file does not already exists:如果文件尚不存在,我正在尝试通过以下方法在 python 中创建一个 new.txt 文件:

company_name_file = open(company_name_file.txt, "r")

company_name_file.close()

But, it is not creating a new file if the file name does not exists.但是,如果文件名不存在,则不会创建新文件。 Any help would be appreciated!任何帮助,将不胜感激!

You need to change the "r" to a "w+".您需要将“r”更改为“w+”。 r represents the read mode and w represents the write mode Currently, your code is trying to read a file rather than write a file. r代表读取模式, w代表写入模式 目前,您的代码正在尝试读取文件而不是写入文件。

with open("company_name_file.txt", "w+") as company_name_file:
    company_name_file.write("Test")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM