14Dealing with Files
Thus far we have gone through what you can do with Python and the examples given have revolved around simple examples. In reality we want to work on data of some kind and as such we need to get it into Python. Now, we can obtain our data from a variety of sources such as databases, web API's but a common way to obtain data is through a good old fashioned file. So in this section, we will use a lot of what we have learnt so far to deal with reading data from and writing to files.
Python can read files pretty easily from the standard library. Its just a case of specifying where the file is and then creating a stream to that location. Let's demonstrate by having a file located in /Path/to/file/test.csv. This is the full path to the comma separated file test.csv.
What we have done here is define a string file_name containing the name of the file and then used the open command with the arguments of file_name and ‘r’ which is the mode to read the file in and in this case it refers to read. We have assigned the return of this to the variable f which is a stream to the file. Now to read in the data from the file we simply run:
What we get back is the data in a single index list, which isn't that useful. In text files what you find is that lines are separated ...