Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is meant by "truncates the file" RE file.open(w+b)?

The default mode is 'r' (open for reading text, synonym of 'rt'). Modes 'w+' and 'w+b' open and truncate the file. Modes 'r+' and 'r+b' open the file with no truncation.
Which do I use if I want to seek within a file in binary mode, write to it in an overwrite rather than insertion mode, and close it?

edit

Also how would I convert a string "7F" or "1A" from a string representation of a hexadecimal number into a decimal number?

double edit

I think this should work for the last question.
int("7F",16)
int("1A",16)
int(lineList[3][n:n+1],16)

Here's the code for my script.
import sys,io

csvName = sys.argv[1]
with open(csvName, "r") as f:
line = f.readline()
while line != '':
lineList = line.split(',')
with open(lineList[0],"w+b") as writeFile:
#waiting on python forum reply for above
writeFile.seek(int(lineList[1]))
#next do a loop where you grab lineList[3][n:n+1],
#convert it from a hex string to an int,
#and write it.
#maybe int(lineList[3][n:n+1],16)
line = f.readline()

#file.seek(36,0)
#address = file.read(1)[0]
#address = ((file.read(1)[0] << 8) | address)
#address = ((file.read(1)[0] << 16) | address)
#address = ((file.read(1)[0] << 24) | address)
#print(str(address))
#print(hex(address))
#open csv file
#while (readfirstline() != EOF)
#{
# split line along commas
# open file in first element in array or list as write binary
# seek to addresss in second element in array or list
# convert third line into format writable to binary file
# write third line
# close file
#}

#just operating on one file, don't need this for loop or wildcards
by

1 Answer

Bharatv4tg1
The "wb truncates" means that opening a file with "w" (the "b" doesn't matter for this) resets the file to empty. Truncates is not a great choice of words because we are used to "truncate to a value" or "truncate to a precision". Here it means "truncate to 0 bytes".

There is only one place you should ever write to a file, after the end. You can do this with an empty file, or with a file that contains values. You need to be really careful when trying to write anywhere else.

Login / Signup to Answer the Question.