Created
October 25, 2013 22:08
-
-
Save damianesteban/7162573 to your computer and use it in GitHub Desktop.
Example of reading/writing files in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Read It | |
# Demonstrates reading from a text file | |
print("Opening and closing the file.") | |
text_file = open("read_it.txt", "r") | |
text_file.close() | |
print("\nReading characters and closing the file.") | |
text_file = open("read_it.txt", "r") | |
print(text_file.read(1)) | |
print(text_file.read(5)) | |
text_file.close() | |
print("\nReading the entire file at once.") | |
text_file = open("read_it.txt", "r") | |
whole_thing = text_file.read() | |
print(whole_thing) | |
text_file.close() | |
print("\nReading characters from a line.") | |
text_file = open("read_it.txt", "r") | |
print(text_file.readline(1)) | |
print(text_file.readline(5)) | |
text_file.close() | |
print("\nReading one line at a time.") | |
text_file = open("read_it.txt", "r") | |
lines = text_file.readlines() | |
print(lines) | |
print(len(lines)) | |
for line in lines: | |
print(line) | |
text_file.close() | |
print("\nLooping through the file, line by line") | |
text_file |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment