2017-04-25 Files

posted Apr 25, 2017, 6:13 AM by Samuel Konstantinovich
Attached are two files with the same contents. The difference is that they are formatted for windows or linux/mac respectively.

DO NOT open/edit the files! It will potentially change the formatting.


Python can open a file using


Make a new file data.txt and paste in the following:

___________________copy everything after this line------------------
This is a text file.
There are things inside of it!
20 30 40 50
30.4 1.0 3.33 0.6668
___________________copy everything before this line------------------

in the same directory make a python file: loadfile.py

___________________copy everything after this line------------------
#Paste in this code, then test the 3 different read commands.
file = open("data.txt","r")   # r means read mode

#UNCOMMENT ONE of these:
#text = file.read()
#text = file.readlines()
#text = file.readline()
print text
___________________copy everything before this line------------------

In your notes:
Write a description of  what each of the read commands does. 

Now in python:
Use readlines, and you will notice that 2 of the list elements has a string of numbers.

Write some code to split those lines, and try to add the values together.
"20 30 40 50" 

Put that string (from your list of strings) in another variable to make it easier to play around with. 
It can be split up using either : split()   or split(" ")  

Your goal:
Try to add up the values. 

How do you convert a string to an int or floating point number?

Your final goal:
Download the text file attached to this post.
Find the sum of all of the values.


Extra goal:
How would you find the sum of all of these numbers if they were in a text file?
1,2,3,4,5
6,7,8,9,10
12,0,-20,5
1,2,3,4,99




ċ
linux.txt
(1k)
Samuel Konstantinovich,
Apr 25, 2017, 6:13 AM
ċ
windows.txt
(1k)
Samuel Konstantinovich,
Apr 25, 2017, 6:13 AM
Comments