In [ ]:
myfile = open("test.txt", "w")
myfile.write("My first file written from Python\n")
myfile.write("---------------------------------\n")
myfile.write("Hello, world!\n")
myfile.write("Did it work?\n")
myfile.close()
Reading a whole file at once
In [ ]:
f = open("test.txt")
content = f.read()
f.close()
words = content.split()
print("There are {0} words in the file.".format(len(words)))
words
A better way to read files:
with open("somefile.txt" , 'r') as f:
do stuff here...
In [5]:
import urllib.request
with urllib.request.urlopen('http://www.python.org/') as f:
print(f.read(1000))
import urllib.request
url = "https://api.github.com/"
destination_filename = "rfc793.txt"
urllib.request.urlretrieve(url, destination_filename)
We’ll need to get a few things right before this works:
In [13]:
import urllib.request
def retrieve_page(url):
""" Retrieve the contents of a web page.
The contents is converted to a string before returning it.
"""
with urllib.request.urlopen(url) as my_socket:
dta = str(my_socket.read())
return dta
f = open("git.txt", "w")
the_text = retrieve_page("https://reddit.com")
# print(the_text)
Write a program that reads a file and writes out a new file with the lines in reversed order (i.e. the first line in the old file becomes the last one in the new file.)
Write a program that reads a file and prints only those lines that contain the substring snake.
Write a program that reads a text file and produces an output file which is a copy of the file, except the first five columns of each line contain a four digit line number, followed by a space. Start numbering the first line in the output file at 1. Ensure that every line number is formatted to the same width in the output file. Use one of your Python programs as test data for this exercise: your output should be a printed and numbered listing of the Python program.
Write a program that undoes the numbering of the previous exercise: it should read a file with numbered lines and produce another file without line numbers.
Extra: Read through the requests tutorial. Requests is a much better tool for working with HTTP requests than the built in urllib.requests IMHO (it's even recommended in the urllib.requests library!).
In [33]:
code_class = ['dana', 'cole', 'kevin', 'connor', 'jaydn', 'patrick',
'ransom', 'skip', 'mercy', 'nick']
rand_class = code_class.copy()
random.shuffle(rand_class)
list(zip(rand_class, rand_class[::-1]))
Out[33]:
In [ ]: