Files can be read and written into with python.

Plaintext files is just a text file without any information about the font, size or colour. Python files are also example of plaintext files except they have .py file extension.

The other type of file are binary files. These are every other type of file, like pdf, images, exe, etc

open()

There are three steps to reading and writing file in python. First with open() function.
open() will read the file in plaintext read mode. With read mode, we can only read and not modify the file. Read mode is the default mode.

In [1]:
open('F:\\Example\\something.txt')
Out[1]:
<_io.TextIOWrapper name='F:\\Example\\something.txt' mode='r' encoding='cp1252'>
In [2]:
newFile = open('F:\\Example\\something.txt')
In [3]:
newFile.read()
Out[3]:
'This is a text file\nThis is 2nd line'
In [4]:
newFile.close()
In [5]:
newFile.read()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-06070b3d42b7> in <module>()
----> 1 newFile.read()

ValueError: I/O operation on closed file.

If we want to read it again, we would have to open the file again.

In [6]:
newFile = open('F:\\Example\\something.txt')
In [7]:
content = newFile.read()
In [8]:
print(content)
This is a text file
This is 2nd line
In [9]:
newFile.close()

readlines() method.

Returns all lines as strings inside of a list.

In [10]:
newFile = open('F:\\Example\\something.txt')
In [11]:
newFile.readlines()
Out[11]:
['This is a text file\n', 'This is 2nd line']
In [12]:
newFile.close()


Content of the file can be changed if the file is opened in write mode. Write mode will overwrite the file with a blank file and start from scratch

Files can be opened in write mode the following way by passing the second argument w to the open function

In [13]:
newFile = open('F:\\Example\\something.txt', 'w')


Append mode will append the text to the existing file without overwriting the whole file.

Files can be opened in append mode by passing a second argument 'a' to the open function.

In [14]:
newFile = open('F:\\Example\\something.txt', 'a')

In both cases of write mode and append mode, if the file in the path doesn't already exists, python will just create a new blank text file to write to.

In [15]:
newFile = open('F:\\Example\\somenewfile.txt', 'w')

write() method

In [16]:
newFile.write('Hello!!!!!!!!!!!!!!!!')
Out[16]:
21

write() method returns how many bytes of character it wrote to it.

In [17]:
newFile.write('Hello!!!!!!!!!!!!!!!!')
Out[17]:
21
In [18]:
newFile.write('Hello!!!!!!!!!!!!!!!!')
Out[18]:
21
In [19]:
newFile.close()
In [20]:
newFile = open('F:\\Example\\somenewfile.txt')
In [21]:
content = newFile.read()
In [22]:
print(content)
Hello!!!!!!!!!!!!!!!!Hello!!!!!!!!!!!!!!!!Hello!!!!!!!!!!!!!!!!

so by default, write() does not adds a new line to a new addition made with it.

In [23]:
newFile = open('F:\\Example\\somenewfile.txt')
In [24]:
newFile.write('Hello')
---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-24-69872f1e4930> in <module>()
----> 1 newFile.write('Hello')

UnsupportedOperation: not writable

Above is not writable because it is in read mode

In [25]:
newFile = open('F:\\Example\\somenewfile.txt', 'a')
In [26]:
newFile.write('\n\nHello!!!!!')  #\n need to be added to the string in write()
Out[26]:
12
In [27]:
newFile.close()
In [28]:
newFile = open('F:\\Example\\somenewfile.txt') #opening in read mode
In [29]:
content = newFile.read()
In [30]:
print(content)
Hello!!!!!!!!!!!!!!!!Hello!!!!!!!!!!!!!!!!Hello!!!!!!!!!!!!!!!!

Hello!!!!!
In [31]:
newFile.close()


In [32]:
someFile = open('somefile.txt', 'w') #relative file path
In [33]:
someFile.write('Some text in here')
Out[33]:
17
In [34]:
someFile.close()
In [35]:
import os
In [36]:
os.getcwd()
Out[36]:
'C:\\Users\\there\\Python'
In [37]:
os.listdir(os.getcwd())
Out[37]:
['.ipynb_checkpoints',
 '1. Methods on list.ipynb',
 '10. Regex Character Classes and the findall() Method.ipynb',
 '11. Regex Dot Star and the Caret-Dollar Characters.ipynb',
 '12. Regex sub() Method and Verbose Mode.ipynb',
 '13. Regex Example Program.ipynb',
 '14. File names and Absolute-Relative file paths.ipynb',
 '15. Reading and writing Plaintext files.ipynb',
 '2. Similarities Between Lists and Strings.ipynb',
 '3. Dictionary.ipynb',
 '4. String Methods.ipynb',
 '5. String Formatting-String Interpolation.ipynb',
 '6. Launching Python Programmes.ipynb',
 '7. Regular Expression Basics.ipynb',
 '8. Regex Groups and the Pipe Character.ipynb',
 '9. Repetation in Regex Pattern.ipynb',
 'batout.png',
 'batrun.png',
 'cmdhello.png',
 'hellobat.png',
 'hellonotepad.png',
 'hellorun.png',
 'npargv.png',
 'oargv.png',
 'outbat.png',
 'outputbatch.png',
 'photo.jpeg',
 'rargv.png',
 'rh.png',
 'runhello.png',
 'Screenshot_1.png',
 'somefile.txt']

notice the somefile.txt is in the list of files.

In [38]:
someFile = open('somefile.txt', 'a')
In [39]:
someFile.write("This string will be added at the end because it was opened in append mode.")
Out[39]:
74
In [40]:
someFile.close()
In [41]:
read = open('somefile.txt')
In [42]:
content = read.read()
In [43]:
print(content)
Some text in hereThis string will be added at the end because it was opened in append mode.
In [44]:
someFile.close()
In [45]:
read.close()



The shelve Module

Writing and reading a text file is a good way to store single long string. But if we want to store variables that have lists and dictionaries and other complex data structures, we can save variables to binary shelve files using the shelve module

In [46]:
import shelve
In [47]:
shelfFile = shelve.open('mydata')  #shelve.open() returns a shelvefile object

Changes to the shelve value can be made as if it were a dictionary. And when done, call the close on the shelf value.

In [48]:
shelfFile['phones'] = ['s9+', 'pixel2', 'iphonex']  #key is phones
In [49]:
shelfFile.close()



In [50]:
shelfFile = shelve.open('mydata')
In [51]:
shelfFile['phones']
Out[51]:
['s9+', 'pixel2', 'iphonex']
In [52]:
shelfFile.close()


In [53]:
os.getcwd()
Out[53]:
'C:\\Users\\there\\Python'

If I go to above directory, there are three files -
mydata.bak
mydata.dat
mydata.dir
These are the files where the information for the shelve is stored, and they are binary files. i.e. even if the files are opened in notepad, the content will be full of weird characters.


keys() and values() Shelf Methods

ShelfFile objects are very similar to dictionary, they even have the same keys() and values() method that will return a listlike method for all the keys and values inside them.

In [54]:
shelfFile = shelve.open('mydata')
In [55]:
shelfFile.keys()
Out[55]:
KeysView(<shelve.DbfilenameShelf object at 0x000001807A220BE0>)
In [56]:
list(shelfFile.keys())
Out[56]:
['phones']
In [57]:
list(shelfFile.values())
Out[57]:
[['s9+', 'pixel2', 'iphonex']]



-open() will return a file object which has reading and writing related methods.

-Pass 'r' (or nothing) to open() to open file in read mode, 'w' for write mode, 'a' for append mode.

-Opening a nonexistant filename in write or append mode will create that file.

-Call read() or write() to read the contents of a file or write a string to a file.

-Call readlines() to return a list of strings of the file's content

-Call close() when you are done with the file.

-The shelve module can store Python values in a binary file

-shelve.open returns a dictionary-like shelf value.