繁体   English   中英

Python:创建和写入文件错误

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

我在使用Python创建和写入文本文件时遇到麻烦。 我正在运行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")

但是我收到一个TypeError说在text_file = open(text_path, "w")an integer is required (got type str) text_file = open(text_path, "w")

我不知道自己在做什么错,因为我的代码与几个教程站点的代码几乎相同,这些站点显示了如何创建和写入文件。

此外,以上代码是否会创建文本文件(如果不存在),如果不存在,该如何创建?

请不要从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")

因为os模块中还有一个“ open”方法,它将覆盖本机文件的“ open”方法。

暂无
暂无

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

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