Skip to content

Instantly share code, notes, and snippets.

@lfalanga
Last active February 3, 2020 03:00
Show Gist options
  • Save lfalanga/5082787a24a97ccea70caa3d8f72f67b to your computer and use it in GitHub Desktop.
Save lfalanga/5082787a24a97ccea70caa3d8f72f67b to your computer and use it in GitHub Desktop.
# Example 1: Writing to a .txt file
my_list = [i ** 2 for i in range(1, 11)]
# Generates a list of squares of the numbers 1 - 10
f = open("output.txt", "w")
for item in my_list:
f.write(str(item) + "\n")
f.close()
# Example 2: Reading a file
my_file = open("output.txt", "r")
print my_file.read()
my_file.close()
# Example 3: Reading line by line
my_file = open("text.txt", "r")
print my_file.readline()
print my_file.readline()
print my_file.readline()
my_file.close()
# Example 4: Using With/As statement to avoid closing the file
"""
You may not know this, but file objects contain a special pair of built-in
methods: __enter__() and __exit__(). The details aren’t important, but what is
important is that when a file object’s __exit__() method is invoked, it
automatically closes the file. How do we invoke this method? With with and as.
"""
with open("text.txt", "w") as textfile:
textfile.write("Success!")
# Example 5: Verifying if file is closed
with open("text.txt", "w") as my_file:
my_file.write("Success!")
if not my_file.closed:
my_file.close()
print my_file.closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment