Extract lines from file, add to new files
Thomas Passin
list1 at tompassin.net
Thu Jan 11 13:58:07 EST 2024
On 1/11/2024 1:27 PM, MRAB via Python-list wrote:
> On 2024-01-11 18:08, Rich Shepard via Python-list wrote:
>> It's been several years since I've needed to write a python script so I'm
>> asking for advice to get me started with a brief script to separate names
>> and email addresses in one file into two separate files:
>> salutation.txt and
>> emails.txt.
>>
>> An example of the input file:
>>
>> Calvin
>> calvin at example.com
>>
>> Hobbs
>> hobbs at some.com
>>
>> Nancy
>> nancy at herown.com
>>
>> Sluggo
>> sluggo at another.com
>>
>> Having extracted salutations and addresses I'll write a bash script using
>> sed and mailx to associate a message file with each name and email
>> address.
>>
>> I'm unsure where to start given my lack of recent experience.
>>
> From the look of it:
>
> 1. If the line is empty, ignore it.
>
> 2. If the line contains "@", it's an email address.
>
> 3. Otherwise, it's a name.
You could think about a single Python script that looks through your
input file and constructs all the message files without ever writing
separate salutation and address files at all. Then you wouldn't need to
write the sed and mailx scripts. It shouldn't be much harder than
peeling out the names and addresses into separate files.
If you haven't written any Python for some years, the preferred way to
read and write files is using a "with" statement, like this:
with open('email_file.txt', encoding = 'utf-8') as f:
lines = f.readlines()
for line in lines:
if not line.strip(): # Skip blank lines
continue
# Do something with this line
You don't need to close the file because when the "with" block ends the
file will be closed for you.
If the encoding is not utf-8 and you know what it will be, use that
encoding instead.
More information about the Python-list
mailing list