Why do we need to use aliases for file with keyword "as" instead original file name?

Here, course’s example:

import csv
list_of_email_addresses =
with open(‘users.csv’, newline=’’) as users_csv:
user_reader = csv.DictReader(users_csv)
for row in user_reader:
list_of_email_addresses.append(row[‘Email’])

Can we use the origin file name in programs ?

This PythonForBeginners article does a good job of explaining the benefits of using with (and as) over just opening a file.

See also the Python documentation.

3 Likes

Welcome to the forums :slight_smile: !

So think, if we did open the file without a with, we would then have to explicitly close it in a way that was guaranteed.

Remember to format your code with the </> button in the future!

import csv

list_of_email_addresses = []
with open(‘users.csv’, newline=’’) as users_csv:
     user_reader = csv.DictReader(users_csv)
     for row in user_reader:
         list_of_email_addresses.append(row[‘Email’])

@825orion I didn’t see your post as I wrote this! I wasn’t critiquing your explanation :slight_smile:

5 Likes

Yep, that’s pretty much it - saves you from having to use try...finally. :slight_smile:

2 Likes