Working files with Python
All programming languages should manage files properly. Python has different ways to manage files. In this article we are going to discover at least two different ways related to how Python work with files. One of the main reasons why common people and more advanced users are developing in Python is because its capacity of analyze and manage diverse kind of texts and files. The following examples are a demonstration about how easy is manipulate plain text and files from the Python IDLE or writing a Python program.
1. Working with files Line by line:
The main reason why Python can work with files reading only one line at time is for speed reasons. Probably you think that reading line by line could be a slow reading but not necessarily. Sometimes is faster read line by line depending on the type of equipment you are using to deploy the application. This method is recommended when you are operating this reading method in computer with a low memory capacity. The best way to represent this code is as shown in the following example:
- FReadFile = open(sys.argv[1], "r")
- Fline = FReadFile.readline()
- while Fline:
- Fline = FReadFile.readline()
I have used this method in computers with the aforementioned description (low capacity). When you try to perform other reading file method it doesn’t work in the same way. Now you have at least a simple example for reading plain text files. Also you can apply this example to many daily tasks you have in your office or personal project. For instance, I have seen copywriters that are using Python to develop simple applications that are able to read a large list of keywords related to a specific topic such as video games, movies, etc. Also you can have a list of websites or a list of emails that Python is able to read one by one and line by line. For this reason and more you can use Python. It is simple and is fast. Once you make your first test I am very sure you will continue discovering the potential of Python.
2. Reading the file all at once: Reading the entire file at once is another method you can perfectly do it with Python. Sometimes it is the proper method to use if you have to compare to files the most recommended way is this method. Also if you are working with multiple files, check the file line by line could be a problem. You need read the file and read it immediately. It is a popular and widely used method. The following example shows you how easy is write a code for this purpose in Python.
- FReadFile = open(sys.argv[1], "r")
- Fline = FReadFile.readline()
- record = {}
- keycounter = 1
- while Fline:
- key = str(keycounter)
- record[key] = line
- keycounter = keycounter + 1
- Fline = FReadFile.readline()
On the other hand, you can consider apply this example for more and more uses. I give you the example of compare files, but there are further things you can do with this easy example.
