In the blog about counting words, I used the funtion open() to coun the words in that file but I haven’t made a post explaining how to do that, so here it is:
In Python, you don’t need to import any library to read and write files.
The first step is to get a file object.
The way to do this is to use the open function.
A file is usually categorized as either text or binary.
A text file is often structured as a sequence of lines and a line is a sequence
of characters.
The line is terminated by a EOL (End Of Line) character.
The backslash character indicates that the next character will be treated as a
newline.
A binary file is basically any file that is not a text file. Binary files can
only be processed by application that know about the file’s structure.
To open a file for writing use the built-i open() function. open() returns a
file object, and is most commonly used with two arguments.
The syntax is:
file_object = open(filename, mode) where file_object is the variable to put the
file object.
The second argument describes the way in which the file will be used
The mode argument is optional; ‘r’ will be assumed if it’s omitted.
The modes can be:
‘r’ when the file will only be read
‘w’ for only writing (an existing file with the same name will be erased)
‘a’ opens the file for appending; any data written to the file is automatically
added to the end.
‘r+’ opens the file for both reading and writing.
Create a text file
Let’s first create a new text file. You can name it anything you like,
in this example we will name it “newfile.txt”.
file = open(“newfile.txt”, “w”)
file.write(“hello world in the new file
“)
file.write(“and another line
“)
file.close()
How to read a text file
To read a file, we can use different methods.
file.read( )
If you want to return a string containing all characters in the file, you can
use file.read().
file = open(‘newfile.txt’, ‘r’)
print file.read()
Output:
hello world in the new file
and another line
A video that explains it:
Thanks for reading.
Follow me on twitter: @danigguemez
#TC101 #python #files
Sources:http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
https://www.sololearn.com/User/Login/?ReturnUrl=%2fPlay%2fPython