I've got an .obj
file, which is a text file used for 3D graphics, and here's a sample:
f 17439/17439 17440/17440 17441/17441
g lCollar_306
f 17442/17442 17443/17443 17444/17444
f 17445/17445 17446/17446 17447/17447
f 17448/17448 17449/17449 17450/17450
f 17451/17451 17452/17452 17453/17453
f 17454/17454 17455/17455 17456/17456
f 17457/17457 17458/17458 17459/17459
g lShldr_308
f 17460/17460 17461/17461 17462/17462
f 17463/17463 17464/17464 17465/17465
g lCollar_306
I want to go through the file, find each line that starts with the letter 'g'
, and delete the last four characters from each of those lines (removing the underscore and the 3-digit number).
I've tried the following:
for line in data.split('\n'):
if (line.startswith('g')):
line = line.rstrip(line[-4])
That doesn't seem to change anything in the variable data
. I need to get the output as a string that I can save to a file, but I can't seem to get it to work. How do I fix this?
You're splitting your buffer into lines and iterating over them, assigning each one to the variable line
. Then you generate a new string (rstrip
) and assign it back to the variable line
. But that doesn't change the original buffer. You're just generating a new string off to the side and then discarding it.
What you probably want to do is write the lines out to a new file, something like this:
f = open("output.obj", "w")
for line in data.split('\n'):
if line.startswith('g'):
line = line.rstrip(line[-4])
print(line, file=f, end='\n')
f.close()
Notice that here we're doing something with the new line
value (after calling rstrip
).