[Tutor] Editing files through Python

Kent Johnson kent_johnson at skillsoft.com
Mon Aug 30 22:53:15 CEST 2004


Bryan,

Can you show us what you have so far for reading the files? Do you know how 
to write them?

You probably want to process the files line-by-line. There are several ways 
to process strings. If your data is very regular, string.split() might be 
helpful to divide the line up:
 >>> "1, 2, 3, 4, 5, 6, 7, 8, 9, 10".split(", ")
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10\n']

Notice the newline is part of the last split. You can use list slicing to 
drop the end of the list:
 >>> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'][:-5]
['1', '2', '3', '4', '5']

Finally use join to put the list back together for output:
 >>> ", ".join(['1', '2', '3', '4', '5'])
'1, 2, 3, 4, 5'

If your data is not as regular as this, you have to think of another way 
for the program to identify the place to cut the string.

Kent

At 12:38 PM 8/30/2004 -0700, Bryan wrote:
>Hi,
>
>I am a beginner in Python, and this is my first time using this list so I 
>hope my question is acceptable.
>
>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?
>
>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 would like to write a program because I have hundreds of rows like this.
>
>I appreciate any help
>
>Thanks
>Bryan
>
>
>Do you Yahoo!?
><http://us.rd.yahoo.com/mail_us/taglines/10/*http://promotions.yahoo.com/new_mail/static/efficiency.html>New 
>and Improved Yahoo! Mail - Send 10MB messages!
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list