Files belong to the basic data types of the Python language. This is the connecting interface between code and named areas of computer memory. Files perform the function of "canning" objects. They allow you to save any information with its subsequent unloading and processing. Weโll look at how to write to a file in Python and read data back with practical examples.
How to open a file?
Work with this data type starts with the built-in open function. It creates a file object that provides communication with an external document on the computer. After you call the function, you can perform read or write operations to files in Python.
For beginners, working with files will seem difficult. They differ from the usual lines, numbers, dictionaries. To interact with them, literals of sequences or mappings are not used, only methods.
Most of the methods are aimed at performing input and output of information, but there are more specific ones. For example, the instruction output.flush (), which pops output buffers to disk. But we will begin the study of how to open the file.
The first step is to call open (), in parentheses, pass the functions, the name of the external file and the mode of working with it:
- r - means that by default the reading mode will open;
- w - write mode to files in Python;
- a - to record information at the very end of the document;
- b - binary file processing;
- the โ+โ sign means reading and writing at the same time.
An important rule is that all arguments must be specified as string literals, that is, in quotation marks and separated by commas:
- >>> This_file = open ("C: \ odd", "w") # An example of calling the open function in the integrated development environment.
How to use files?
After the file is open, you can use all its methods. Readable content will be presented as strings. To write to files in Python, the information must also be in the form of string objects.
List of most used operations:
- input.read () - will return information as a single string;
- input.readline () - read the next line;
- input.readlines () - present the entire file for reading with a list of lines;
- .write () - write strings;
- .writelines () - record all lines;
- .close () - manually close the document.
Features of working with files
All information contained within files is represented as string objects. Therefore, before proceeding with its processing, you need to perform data conversion. Use the built-in int () or list () methods for this. As well as expressions for formatting strings.
Using the close method is optional. But when working with flush, OS resources are freed up and the output buffers are pushed. By default, output occurs through intermediate buffers. When writing to a file in Python, the information does not immediately go to disk, but only at the time of closing.
Example of writing to a file
Let's look at an example of working with a text file in an interactive session. The first step is to open the file in IDLE. There is no need to create it previously:
- >>> first_f = open ("first_file.txt", "w")
- >>> first_f.write ("Any text \ n") # Write lines
- 12
- >>> first_f.write ("Again, any text \ n")
- 20
- >>> first_f.close () # Close;
- >>> first_f = open ("first_file.txt")
- >>> first_f.readline () # Read what is written
- "Any text \ n"
After writing a string to a file, Python 3.0 returns the number of characters entered. In the previous version this does not happen. The example used the end of line character \ n. Without it, the write method will write everything in solid text.
If you want to read the contents of a file without specifying \ n at the end, use the read method:
- >>> print (open ("first_file.txt"). read ())
- any text;
- and again any text;
You can view each line in turn through iteration:
- >>> for x in open ("first_file.txt"):
- print (x, end = "")
- any text
- and again any text # Each new line will be indented.
Saving base Python objects to a file
You can save any built-in or manually created objects to a text file. To write to files in Python line by line, each element must first be converted to a string. You also need to remember that methods do not format data.
- >>> example_2 = open ("second_file.txt", "w")
- >>> List = [1,8, "r"]
- >>> C, B, P = 34, 90, 56
- >>> Page = "Character Set"
- >>> example_2.write (str (List) + โ\ nโ)
- 12
- >>> example_2.write ("% s,% s,% s \ n"% (C, B, P))
- eleven
- >>> example_2.write (Page + "\ n")
- fifteen
- >>> example_2.close ()
- >>> print (open ("second_file.txt"). read ())
- [1, 8, โrโ]
- 34, 90, 56
- character set
In this example, a new file object โsecond_file.txtโ is first created for recording. Five names are assigned list, string, and integer values. Before recording, each object is converted to a string. At the end, the file is opened using the built-in print function and the read method.
The same principle is used in Python to write a dictionary to a file. You must call the str function and pass it an object as an argument. The hardest thing is not to save the data, but to extract it and turn it back into dictionaries or numbers.
The readline method will help convert strings to language objects:
- >>> L = open ("second_file.txt")
- >>> F = L.readline ()
- >>> F
- "34, 90, 56 \ n"
- >>> Numbers = F.split (",") # Separate by commas
- >>> Numbers
- [โ34โ, โ90โ, โ56 \ nโ]
- >>> Numbers = [int (x) for x in Numbers] # Convert the whole list
- >>> Numbers
- [34, 90, 56]
Recording objects using special modules
The standard library includes a module called pickle. It is an extremely useful tool for recording and retrieving information. Especially when you do not trust the source of the file.
The module is a universal utility that automatically formats and converts data. To write an object of any type (dictionary), it is enough to pass pickle:
- >>> Dictionary = {"eight": 8, "three": 3, "zero": 0}
- >>> Dictionary
- {"Eight": 8, "three": 3, "zero": 0}
- >>> document = open ("my_document.pkl", "wb")
- >>> import pickle
- >>> pickle.dump (Dictionary, document)
- >>> document.close ()
- >>> document = open ("my_document.pkl", "rb")
- >>> D = pickle.load (document)
- >>> D
- {"Eight": 8, "three": 3, "zero": 0}
With the module, there is no need to extract and convert data manually. He himself serializes objects into a string of bytes and vice versa. To do this, wb - write binary is specified in the open arguments.
Like pickle, you can "preserve" data using the Python module - JSON. Writing to a file is done by the dump method. The arguments are stored objects that are automatically serialized to a JSON format string.
- >>> import json
- >>> Dictionary = {"eight": 8, "three": 3, "zero": 0}
- >>> with open ("my_document.json", "w") as m_d:
- >>> json.dump (Dictionary, m_d)
There are more complex ways to work with files. For example, a scan operation, organization of recording cycles. To see the full list of methods, use the help or dir functions in an interactive session. Also in the arsenal of the language there are objects similar to files - sockets, threads of the shell and I / O.