简体   繁体   English

Python:创建和写入文件错误

[英]Python: Creating and writing to a file error

I am having trouble creating and writing to a text file in Python. 我在使用Python创建和写入文本文件时遇到麻烦。 I am running Python 3.5.1 and have the following code to try and create and write to a file: 我正在运行Python 3.5.1,并具有以下代码来尝试创建和写入文件:

from os import *
custom_path = "MyDirectory/"
if not path.exists(custom_path)
    mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, "w")
text_file.write("my text")

But I get a TypeError saying an integer is required (got type str) at the line text_file = open(text_path, "w") . 但是我收到一个TypeError说在text_file = open(text_path, "w")an integer is required (got type str) text_file = open(text_path, "w")

I don't know what I'm doing wrong as my code is just about identical to that of several tutorial sites showing how to create and write to files. 我不知道自己在做什么错,因为我的代码与几个教程站点的代码几乎相同,这些站点显示了如何创建和写入文件。

Also, does the above code create the text file if it doesn't exist, and if not how do I create it? 此外,以上代码是否会创建文本文件(如果不存在),如果不存在,该如何创建?

Please don't import everything from os module: 请不要从os模块导入所有内容:

from os import path, mkdir
custom_path = "MyDirectory/"
if not path.exists(custom_path):
    mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, 'w')
text_file.write("my text")

Because there also a "open" method in os module which will overwrite the native file "open" method. 因为os模块中还有一个“ open”方法,它将覆盖本机文件的“ open”方法。

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

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