简体   繁体   中英

Python: Opening a file with defined drive letter - TypeError: an integer is required

Here is my two lines of code:

drive = 'j:'
f = open("%s\sample", "wb", drive)

I'm trying to write a simple program that is writing to a file that is being created by the program, the file is to be created on a defined drive, in this case, just onto "J:", however the following is displayed when running the code:

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

Am I missing something simple here?

drive = 'j:'
f = open("%s\sample" % drive, "wb")

Guess this is what you want.

You should use with to open your files as it will automatically close them and str.format may be less prone to simple errors:

drive = 'j:'
with open("{}/sample".format(drive), "wb", drive) as f:
     ..........

You should also use / or raw string r in your file paths as \\ is used to escape characters in python.

You can see how not doing so can have very different outcome:

In [38]: print "\new_dir"

ew_dir

In [39]: print "/new_dir"
/new_dir

In [40]: print r"\new_dir"
\new_dir

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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