Python write into text

How to Write to a Text File in Python

In Python, you can write to a text file by following these three steps:

You can skip the last step by using the with statement.

with open("example.txt", "w") as f: f.write("Hello world!")

This piece of code creates a new file called example.txt and writes “Hello World” into it.

In this guide, you are going to learn the basics of writing to a file in Python.

Python How to Write to a File in Detail

To write to a file in Python, use these three steps:

  1. Open a text file with the open() function.
  2. Write text to the opened file with the write() method.
  3. Finally, close the file using the close() method. Another options is to use the with statement that automatically closes the file for you. In this guide, I’m going to use the with statement.
Читайте также:  Java home bin directory

The syntax for the open() function is as follows:

  1. path_to_a_file is the path to the file you want to open. If no file is found, a new one is created.
  2. mode specifies in which state you want to open the file. Use the mode ‘w’ to write to the file and ‘a’ to append to a file (add text to the end of the file).

The open() function returns a file object. This file object has two useful methods for writing text to the file:

  1. write() that writes a single string to the text file.
  2. writelines() that writes a list of strings to the file (or any other iterable, such as a tuple or set of strings).

Let’s see how to use these file-writing methods.

The write() Method in Python

The write() method takes a string argument. It writes this argument into the opened file.

For example, let’s create a list of strings and use the write() method to write each of the strings into the file using a for loop:

words = ["This ", "is ", "a ", "test"] with open("example.txt", "w") as f: for word in words: f.write(word)

As a result, a file called example.txt is created with the following content:

Notice how each string is written to the same line by default.

If you want to have each word appear on a separate line, write the line break character ‘\n’ after writing a string to the file.

words = ["This", "is", "a", "test"] with open("example.txt", "w") as f: for word in words: f.write(word) f.write("\n")

In the example.txt file the result looks like this:

This is one way to write into a file.

But in the case of multiple strings, you can use the writelines() method to write them all into a file on the same go.

The writelines() Method in Python

The writelines() function takes an iterable object, such as a list, that contains strings to be written into the opened file.

For example, let’s repeat the above example using the writelines() method:

words = ["This ", "is ", "a ", "test"] with open("example.txt", "w") as f: f.writelines(words)

After running this piece of code, the example.txt file looks like this:

Now you know how to write text to a file in Python.

Next, let’s take a look at how to add text at the end of an already-existing text file.

How to Append to a File in Python

To add text at the end of a file after the existing lines of text, use the write mode ‘a’.

This mode is called the appending mode. Appending means adding to the end of something.

# Let's first write to a file with open("example2.txt", "w") as f: f.write("This is ") # Then let's reopen the file and append some text to it: with open("example2.txt", "a") as f: f.write("just another test.")

Here the result is a file called example2.txt with the following contents:

This is just another test.

As you can see, the last bits of text were successfully added to the end of the text file.

Conclusion

Today you learned how to write a file in Python.

To recap, to write a file, follow these three steps:

  1. Open the file with the open() function.
  2. Write to the file using either write() or writelines() method.
  3. Always close the file after writing. You can do this with the close() method or by using the with statement that automatically closes the file after writing.

See Also

Источник

Python Write Text File

Python provides built-in functions to perform file operations, such as creating, reading, and writing files. There are mainly two types of files that Python can handle, normal text files and binary files. In this tutorial, we will look at how to write content into text files in Python.

Steps on How to write to a File in Python

In order to write to a text file in Python, you need to follow the below steps.

Step 1: The file needs to be opened for writing using the open() method and pass a file path to the function.

Step 2: The next step is to write to file, and this can be achieved using several built-in methods such as write() , writelines() .

Step 3: Once the write operation is performed, the text file must be closed using the close() function.

Now that we have seen the steps to write to a text file let’s understand each of these methods before getting into examples.

Python open() function

The open() function opens the file if possible and returns the corresponding file object.

Syntax – open(file, mode=’w’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

The open() function has a lot of parameters. Let’s take a look at the necessary params for writing to a text file. It opens the file in a specified mode and returns a file object.

  • file – path like object which represents the file path
  • mode (Optional) – The mode is an optional parameter. It’s a string that specifies the mode in which you want to open the file.

Methods for Writing to a text file in Python

  1. write() : The write() function will write a line to a text file. It inserts a single line in the text file.
  2. writelines() : The writelines() function will write multiple string lines at once to a text file. The writelines() method accepts an iterable object such as list, set, tuple, etc.

Python close() function

The file will remain open until you close the file using the close() function. It is a must and best practice to perform this operation after writing the data into the file as it frees up the memory space acquired by that file. Otherwise, it may cause an unhandled exception.

We can use the with statement, which helps to close the file once the write operation is performed. We don’t have to specify any explicit close method everytime.

Examples for Writing to Text file in Python

Example 1 – Write a line to a text file using the write() function

Let’s look at writing a line into a text file using the write() method. We will use the with statement, which helps to close the file once the write operation is performed. We don’t have to specify any explicit close method.

# Program to write to text file using write() function with open("python.txt", "w") as file: content = "Hello, Welcome to Python Tutorial !! \n" file.write(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello, Welcome to Python Tutorial !! 

Example 2 – Append a line to a text file using the write() function

If you want to append the line to the existing text file, you need to open the file in the append mode first and perform the write() operation, as shown below.

# Program to append to text file using write() function with open("python.txt", "a") as file: content = "Append the content at the end \n" file.write(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello, Welcome to Python Tutorial !! Append the content at the end

Example 3 – Write a list to a file using the writelines() function

Let’s look at writing multiple lines into a text file using the writelines() method. The writelines() method accepts an iterable object such as list, set, tuple, etc. In the below example let’s see how to write a list to a file in Python

Syntax of writelines()

file.writelines(list)

list – The list of texts or byte objects that will be inserted. It can be a list, tuple, set of strings, etc.

# Program to write multiple lines to text file using writelines() function with open("python.txt", "w") as file: content = ["Hello\n", "Welcome to Python Tutorial\n", "Cheers \n" ] file.writelines(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello Welcome to Python Tutorial Cheers

Example 4 – Append multiple lines to a text file using the writelines() function

If you want to append multiple lines to the existing text file, you need to open the file in the append mode first and perform the writelines() operation, as shown below.

# Program to append to text file using writelines() function with open("python.txt", "a") as file: content = ["Appending the content\n", "Python\n" ] file.writelines(content) file.close() # Program to read the entire file (absolute path) using read() function with open("C:/Projects/Tryouts/python.txt", "r") as file: content = file.read() print(content) file.close()
Hello Welcome to Python Tutorial Cheers Appending the content 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.

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.

Источник

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