Work with text in python

Reading and Writing to text files in Python

Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s).

  • Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is the new line character (‘\n’) in python by default.
  • Binary files: In this type of file, there is no terminator for a line, and the data is stored after converting it into machine-understandable binary language.

In this article, we will be focusing on opening, closing, reading, and writing data in a text file.

File Access Modes

Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once its opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python.

  1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises the I/O error. This is also the default mode in which a file is opened.
  2. Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exist.
  3. Write Only (‘w’) : Open the file for writing. For the existing files, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exist.
  4. Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
  5. Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
  6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Читайте также:  Learn Jquery Css Method

How Files are Loaded into Primary Memory

There are two kinds of memory in a computer i.e. Primary and Secondary memory every file that you saved or anyone saved is on secondary memory cause any data in primary memory is deleted when the computer is powered off. So when you need to change any text file or just to work with them in python you need to load that file into primary memory. Python interacts with files loaded in primary memory or main memory through “file handlers” ( This is how your operating system gives access to python to interact with the file you opened by searching the file in its memory if found it returns a file handler and then you can work with the file ).

Opening a File

It is done using the open() function. No module is required to be imported for this function.

File_object = open(r"File_Name","Access_Mode")

The file should exist in the same directory as the python program file else, the full address of the file should be written in place of the filename. Note: The r is placed before the filename to prevent the characters in the filename string to be treated as special characters. For example, if there is \temp in the file address, then \t is treated as the tab character, and an error is raised of invalid address. The r makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file is in the same directory and the address is not being placed.

Источник

Working with Text Files in Python

Bespectacled man reading an alphabet book

In this lesson you will learn how to manipulate text files using Python.

edited by

reviewed by

published

modified

difficulty

DOI id icon

https://doi.org/10.46430/phen0020

Great Open Access tutorials cost money to produce. Join the growing number of people supporting Programming Historian so we can continue to share knowledge free of charge.

Contents

Lesson Goals

In this lesson you will learn how to manipulate text files using Python. This includes opening, closing, reading from, and writing to .txt files using programming.

The next few lessons in this series will involve downloading a web page from the Internet and reorganizing the contents into useful chunks of information. You will be doing most of your work using Python code written and executed in Komodo Edit.

Working with Text Files

Python makes it easy to work with files and text. Let’s begin with files.

Creating and Writing to a Text File

Let’s start with a brief discussion of terminology. In a previous lesson (depending on your operating system: Mac Installation, Windows Installation, or Linux Installation), you saw how to send information to the “Command Output” window of your text editor by using Python’s print command.

Читайте также:  Сортировка log n java

The Python programming language is object-oriented. That is to say that it is constructed around a special kind of entity, an object, which contains both data and a number of methods for accessing and altering that data. Once an object is created, it can interact with other objects.

In the example above, we see one kind of object, the string “hello world”. The string is the sequence of characters enclosed by quotes. You can write a string one of three ways:

message1 = 'hello world' message2 = "hello world" message3 = """hello hello hello world""" 

The important thing to note is that in the first two examples you can use single or double quotes / inverted commas, but you cannot mix the two within one string.

For instance, the following are all wrong:

message1 = "hello world' message2 = 'hello world" message3 = 'I can't eat pickles' 

Count the number of single quotes in message3. For that to work you would have to escape the apostrophe:

message3 = 'I can\'t eat pickles' 
message3 = "I can't eat pickles" 

In the third example, the triple quotes signify a string that covers more than one line.

Print is a command that prints objects in textual form. The print command, when combined with the string, produces a statement.

You will use print like this in cases where you want to create information that needs to be acted upon right away. Sometimes, however, you will be creating information that you want to save, to send to someone else, or to use as input for further processing by another program or set of programs. In these cases you will want to send information to files on your hard drive rather than to the “Command Output” pane. Enter the following program into your text editor and save it as file-output.py .

# file-output.py f = open('helloworld.txt','w') f.write('hello world') f.close() 

In Python, any line that begins with a hash mark (#) is known as a comment and is ignored by the Python interpreter. Comments are intended to allow programmers to communicate with one another (or to remind themselves of what their code does when they sit down with it a few months later). In a larger sense, programs themselves are typically written and formatted in a way that makes it easier for programmers to communicate with one another. Code that is closer to the requirements of the machine is referred to as low-level, whereas code that is closer to natural language is high-level. One of the benefits of using a language like Python is that it is very high level, making it easier for us to communicate with you (at some cost in terms of computational efficiency).

Читайте также:  Read text file with java

In this program f is a file object, and open , write and close are file methods. In other words, open, write and close do something to the object f which is in this case defined as a .txt file. This is likely a different use of the term “method” than you might expect and from time to time you will find that words used in a programming context have slightly (or completely) different meanings than they do in everyday speech. In this case recall that methods are bits of code which perform actions. They do something to something else and return a result. You might try to think of it using a real-world example such giving commands to the family dog. The dog (the object) understands commands (i.e., has “methods”) such as “bark”, “sit”, “play dead”, and so on. We will discuss and learn how to use many other methods as we go along.

f is a variable name chosen by us; you could have named it just about anything you like. In Python, variable names can be made from upper- and lowercase letters, numbers and underscores…but you can’t use the names of Python commands as variables. If you tried to name your file variable “print” for example, your program would not work because that is a reserved word that is part of the programming language.

Python variable names are also case-sensitive, which means that foobar, Foobar and FOOBAR would all be different variables.

When you run this program, the open method will tell your computer to create a new text file helloworld.txt in the same folder as you have saved the file-output.py program. The w parameter says that you intend to write content to this new file using Python.

Note that since both the file name and the parameter are surrounded by single quotes you know they are both stored as strings; forgetting to include the quotation marks will cause your program to fail.

On the next line, your program writes the message “hello world” (another string) to the file and then closes it. (For more information about these statements, see the section on File Objects in the Python Library Reference.)

Double-click on your “Run Python” button in Komodo Edit to execute the program (or the equivalent in whichever text-editor you have decided to use: e.g., click on the “#!” and “Run” in TextWrangler). Although nothing will be printed to the “Command Output” pane, you will see a status message that says something like

`/usr/bin/python file-output.py` returned 0. 
'C:\Python27\Python.exe file-output.py' returned 0. 

Источник

Оцените статью