Python Help To Debug An Error When Modify A File In A Stream Mode
Solution 1:
opening the line in r+ mode means that you read a line, ie 38 characters read. Then you modify those 38 characters Then, at the current file position (character 39) you over write the existing data
I would guess this is not what you want
Hope this helps
Solution 2:
This just isn't going to work. As Martijn said,
I
file
objects have a buffer position. Every time you read a character the buffer position advances by 1. Suppose you read a line that's 10 characters long:
>>>myfile = open('some_file.txt')>>>myfile.tell() #gets the buffer position
0
>>>myfile.readline()
'012345678\n'
Now the buffer position is advanced by len(line)
characters:
>>>myfile.tell()
10
This means that when you call myfile.write()
, it starts writing at position 10.
II
You simply can't "insert" characters into a file without overwriting something, or appending characters to the end (assuming that the buffer position is at the end of the file).
So what do you do?
You can create a temporary file, and simultaneously read from your input file, and write to your temp file. Afterwards (if you should wish), you can replace your original file with the temporary one:
withopen(input_file) as infile, open(output_temp_file, "w") as outfile:
for line in infile:
x, y, z = line.split()
new_line = ' '.join([x, y, z] + [function_of_xyz(x, y, z)]) + '\n'
outfile.write(new_line)
You should also check out the csv
module.
Post a Comment for "Python Help To Debug An Error When Modify A File In A Stream Mode"