[英]TypeError: an integer is required (got type str) when opening file in Python
[英]Python: Opening a file with defined drive letter - TypeError: an integer is required
这是我的两行代码:
drive = 'j:'
f = open("%s\sample", "wb", drive)
我正在尝试编写一个简单的程序,该程序正在写入由程序创建的文件,该文件将在已定义的驱动器上创建,在这种情况下,只是在“J:”上,但是会显示以下内容运行代码时:
Traceback (most recent call last):
File "D:\FYP\Program\usb.py", line 2, in <module>
f = open("%s\sample", "wb", drive)
TypeError: an integer is required
我错过了一些简单的东西吗?
drive = 'j:'
f = open("%s\sample" % drive, "wb")
猜猜这就是你想要的。
您应该使用with
来打开文件,因为它会自动关闭它们,而str.format可能不太容易出现简单的错误:
drive = 'j:'
with open("{}/sample".format(drive), "wb", drive) as f:
..........
您还应该在文件路径中使用/
或原始字符串r
,因为\\
用于转义python中的字符。
你可以看到不这样做会有什么不同的结果:
In [38]: print "\new_dir"
ew_dir
In [39]: print "/new_dir"
/new_dir
In [40]: print r"\new_dir"
\new_dir
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.