I can read your mind

Reading files sounds very complicated, but is very easy an this GIF explains it very well

Reading-Text-File-Animation-s

And…what about if I want to make a list out of a bunch of words separated by a comma or semi-colon, well we have a GIF for explaining this, here you will use the split() method.

Reading-CSV-File-Animation-s

Here we have an example from our friends of 101Computing

The code below realizes 5 main steps:

  1. Step 1: Open the text file using the open() function. This function takes two parameters: The name of the file (e.g. “playlist.txt”) and the access mode. In our case we are opening the file in read-only mode: “r”.
  2. Read through the file one line at a time using a for loop.
  3. Split the line into an array. This is because in this file each value is separated with a semi-column. By splitting the line we can then easily access each value (field) individually.
  4. Output the content of each field using the print method.
  5. Once the for loop is completed, close the file using the close() method.

https://www.trinket.io/embed/python/2d1f14806c

Here we have the «modes» available for open() 

Mode Description
r Opens a file in read only mode. This is the default mode.
r+ Opens a file for both reading and writing.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
w+ Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
a Opens a file for appending. The file pointer is at the end of the file. So new data will be added at the end of the file. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

References:

http://www.101computing.net/python-reading-a-text-file/

Deja un comentario