{Spam?} [Tutor] Editing files through Python

Bob Gailer bgailer at alum.rpi.edu
Mon Aug 30 23:00:21 CEST 2004


At 01:38 PM 8/30/2004, Bryan wrote:
>
>I am a beginner in Python, and this is my first time using this list so I 
>hope my question is acceptable.

We are here to help, but not just give answers. However your request seems 
to me to merit a program, which I hope you will study to enhance your 
understanding of Python. Please ask more questions.,

>Basically, my goal is to read data files that are already on my hard drive 
>into Python, and then edit them, deleting unneccesary portions of data.
>
>I have already figured out how to read the files into Python, I just 
>cannot figure out how to edit them.  Here are the difficulties:
>
>How do I delete, cut, or paste portions of the data I am reading and how 
>do I tell the program to jump to that specific portion of data that I want 
>to alter?

The usual approach is to read the file into a Python variable, process the 
variable and write a new file (which can have the same name as the input 
file, rather than to attempt to manipulate the file itself. It is a LOT 
easier this way.

>  Here is a somewhat complicated example, similar to what I want to do -
>
>I have two rows of numbers, as shown below.  Each row has 10 numbers 
>(hopefully they will show up as two rows of numbers in the email (1-10 and 
>11-20).
>
>1, 2, 3, 4, 5, 6, 7, 8, 9, 10
>11, 12, 13, 14, 15, 16, 17, 18, 19, 20
>
>What commands might I use to automatically go through each row, deleting 
>the 6th through 10th numbers in each row (6-10 in the first row and 16-20 
>in the second row).

I have written a complete program, just to avoid any ambiguities.

input_file = file('num.txt', 'r') # substitute your path to the file
lines = input_file.readlines() # list of lines
output_file = file('num.txt', 'w') # substitute your path to the file
for line in lines:
   nums = line.split(", ") # assumes numbers separated by ", ", gives list 
of numbers
   retain = nums[:5] # keep first 5 numbers
   new_line = ", ".join(retain)+"\n" # reassemble into a line
   output_file.write(new_line) # write to file
output_file.close()

Please note this depends on consistent number separators. If the separators 
vary, then the approach gets more complex.

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell 



More information about the Tutor mailing list