• Python »
  • 3.12.2 Documentation »
  • The Python Tutorial »
  • 7. Input and Output
  • Theme Auto Light Dark |

7. Input and Output ¶

There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities.

7.1. Fancier Output Formatting ¶

So far we’ve encountered two ways of writing values: expression statements and the print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout . See the Library Reference for more information on this.)

Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.

To use formatted string literals , begin a string with f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

The str.format() method of strings requires more manual effort. You’ll still use { and } to mark where a variable will be substituted and can provide detailed formatting directives, but you’ll also need to provide the information to be formatted.

Finally, you can do all the string handling yourself by using string slicing and concatenation operations to create any layout you can imagine. The string type has some methods that perform useful operations for padding strings to a given column width.

When you don’t need fancy output but just want a quick display of some variables for debugging purposes, you can convert any value to a string with the repr() or str() functions.

The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is no equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr() . Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings, in particular, have two distinct representations.

Some examples:

The string module contains a Template class that offers yet another way to substitute values into strings, using placeholders like $x and replacing them with values from a dictionary, but offers much less control of the formatting.

7.1.1. Formatted String Literals ¶

Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression} .

An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal:

Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.

Other modifiers can be used to convert the value before it is formatted. '!a' applies ascii() , '!s' applies str() , and '!r' applies repr() :

The = specifier can be used to expand an expression to the text of the expression, an equal sign, then the representation of the evaluated expression:

See self-documenting expressions for more information on the = specifier. For a reference on these format specifications, see the reference guide for the Format Specification Mini-Language .

7.1.2. The String format() Method ¶

Basic usage of the str.format() method looks like this:

The brackets and characters within them (called format fields) are replaced with the objects passed into the str.format() method. A number in the brackets can be used to refer to the position of the object passed into the str.format() method.

If keyword arguments are used in the str.format() method, their values are referred to by using the name of the argument.

Positional and keyword arguments can be arbitrarily combined:

If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys.

This could also be done by passing the table dictionary as keyword arguments with the ** notation.

This is particularly useful in combination with the built-in function vars() , which returns a dictionary containing all local variables.

As an example, the following lines produce a tidily aligned set of columns giving integers and their squares and cubes:

For a complete overview of string formatting with str.format() , see Format String Syntax .

7.1.3. Manual String Formatting ¶

Here’s the same table of squares and cubes, formatted manually:

(Note that the one space between each column was added by the way print() works: it always adds spaces between its arguments.)

The str.rjust() method of string objects right-justifies a string in a field of a given width by padding it with spaces on the left. There are similar methods str.ljust() and str.center() . These methods do not write anything, they just return a new string. If the input string is too long, they don’t truncate it, but return it unchanged; this will mess up your column lay-out but that’s usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in x.ljust(n)[:n] .)

There is another method, str.zfill() , which pads a numeric string on the left with zeros. It understands about plus and minus signs:

7.1.4. Old string formatting ¶

The % operator (modulo) can also be used for string formatting. Given 'string' % values , instances of % in string are replaced with zero or more elements of values . This operation is commonly known as string interpolation. For example:

More information can be found in the printf-style String Formatting section.

7.2. Reading and Writing Files ¶

open() returns a file object , and is most commonly used with two positional arguments and one keyword argument: open(filename, mode, encoding=None)

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

Normally, files are opened in text mode , that means, you read and write strings from and to the file, which are encoded in a specific encoding . If encoding is not specified, the default is platform dependent (see open() ). Because UTF-8 is the modern de-facto standard, encoding="utf-8" is recommended unless you know that you need to use a different encoding. Appending a 'b' to the mode opens the file in binary mode . Binary mode data is read and written as bytes objects. You can not specify encoding when opening file in binary mode.

In text mode, the default when reading is to convert platform-specific line endings ( \n on Unix, \r\n on Windows) to just \n . When writing in text mode, the default is to convert occurrences of \n back to platform-specific line endings. This behind-the-scenes modification to file data is fine for text files, but will corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files.

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point. Using with is also much shorter than writing equivalent try - finally blocks:

If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it.

Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

After a file object is closed, either by a with statement or by calling f.close() , attempts to use the file object will automatically fail.

7.2.1. Methods of File Objects ¶

The rest of the examples in this section will assume that a file object called f has already been created.

To read a file’s contents, call f.read(size) , which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size characters (in text mode) or size bytes (in binary mode) are read and returned. If the end of the file has been reached, f.read() will return an empty string ( '' ).

f.readline() reads a single line from the file; a newline character ( \n ) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n' , a string containing only a single newline.

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:

If you want to read all the lines of a file in a list you can also use list(f) or f.readlines() .

f.write(string) writes the contents of string to the file, returning the number of characters written.

Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary mode) – before writing them:

f.tell() returns an integer giving the file object’s current position in the file represented as number of bytes from the beginning of the file when in binary mode and an opaque number when in text mode.

To change the file object’s position, use f.seek(offset, whence) . The position is computed from adding offset to a reference point; the reference point is selected by the whence argument. A whence value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the file as the reference point. whence can be omitted and defaults to 0, using the beginning of the file as the reference point.

In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2) ) and the only valid offset values are those returned from the f.tell() , or zero. Any other offset value produces undefined behaviour.

File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.

7.2.2. Saving structured data with json ¶

Strings can easily be written to and read from a file. Numbers take a bit more effort, since the read() method only returns strings, which will have to be passed to a function like int() , which takes a string like '123' and returns its numeric value 123. When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated.

Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation) . The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing . Reconstructing the data from the string representation is called deserializing . Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.

The JSON format is commonly used by modern applications to allow for data exchange. Many programmers are already familiar with it, which makes it a good choice for interoperability.

If you have an object x , you can view its JSON string representation with a simple line of code:

Another variant of the dumps() function, called dump() , simply serializes the object to a text file . So if f is a text file object opened for writing, we can do this:

To decode the object again, if f is a binary file or text file object which has been opened for reading:

JSON files must be encoded in UTF-8. Use encoding="utf-8" when opening JSON file as a text file for both of reading and writing.

This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the json module contains an explanation of this.

pickle - the pickle module

Contrary to JSON , pickle is a protocol which allows the serialization of arbitrarily complex Python objects. As such, it is specific to Python and cannot be used to communicate with applications written in other languages. It is also insecure by default: deserializing pickle data coming from an untrusted source can execute arbitrary code, if the data was crafted by a skilled attacker.

Table of Contents

  • 7.1.1. Formatted String Literals
  • 7.1.2. The String format() Method
  • 7.1.3. Manual String Formatting
  • 7.1.4. Old string formatting
  • 7.2.1. Methods of File Objects
  • 7.2.2. Saving structured data with json

Previous topic

8. Errors and Exceptions

  • Report a Bug
  • Show Source

How to Write to File in Python

Author's photo

  • python basics

With Python, you can modify and write directly to a file programmatically, saving you the hassle of doing it manually. In this article, you will learn how to write to a file in Python.

Before diving into the nitty-gritty of how to write to file in Python, I want to mention that I use Python 3.8.5 and Windows 10. However, your results should be the same on any operating system.

It’s good to have some knowledge of file manipulation before you read this article. For more information, read How to Work with Files and Directories in Python and How to Rename Files with Python .

There are multiple ways to write to files and to write data in Python. Let’s start with the write() method.

Use write() to Write to File in Python

The first step to write a file in Python is to open it, which means you can access it through a script. There are two ways to open a file. The first one is to use open() , as shown below:

However, with this method, you need to close the file yourself by calling the close() method:

It is shorter to use the with statement, as we do not need to call the close() method.

This is the method we’ll use in this tutorial:

The above line of code will open file.txt and will assign the file handler to the variable called file .

We can then call the write() method to modify our file programmatically.

Let’s run an example:

Once this command has been executed, we want to read the file to see if it has been updated. We need to call the read() method, as shown below:

It’s important to note that the parameters in the open() function will decide where the write() method will be active.

If you want to learn more on how to write files in Python with the write() method, check out our course on Working with Files and Directories in Python .

Use writelines() to Add List Data to a File

Another method that you can use is writelines() . This method adds terms of a list in a programmatic way.  Let’s run an example:

After checking the output, you will notice that writelines() does not add any line separators by default; we have to specify the line separator. We can modify our code with the following:

A more Pythonic and efficient way of doing it is:

The code above will use new lines as the line separator.

Writing Data to CSV Files in Python

You might find it useful to be able to update a CSV file directly with Python.

CSV stands for comma-separated values. If you are a data professional, you’ve certainly come across this kind of file. A CSV file is a plain text file containing a list of data. This type of file is often used to exchange data between applications. If you want to refresh your knowledge of CSV files, read our article How to Read CSV Files in Python .

In this part, we will use Python’s built-in csv module to update a CSV file.

When you want to write data to a file in Python, you’ll probably want to add one or more rows at once. The data can be stored in lists or a dictionary. Let’s explore some ways to write data to files in Python.

Writing List Data to a CSV

Let’s explore how to add a single row of data with writerow() and multiple rows of data with writerows() .

Use writerow() for a Single Row

To write in a CSV file, we need to open the file, create a writer object and update the file. Let’s run an example:

For detailed information, it’s always a good idea to read the documentation .

Now, let’s explore how to write data in Python when you need to add multiple rows of data.

Use writerows() for Multiple Rows

We can write multiple rows to a file using the writerows() method:  

We just added several rows to our file.

You can find more information about the writerows() method in the documentation .

Writing Dictionary Data to a CSV

If each row of the CSV file is a dictionary, you can update that file using the csv module’s dictWriter() function. For example:

And that’s all you have to do!

If you want to learn more on the topic, do not forget to check the course on working with files and directories in Python .

Using pathlib to Write Files in Python

Now let’s explore using the pathlib module to write to a file in Python. If you are not familiar with pathlib, see my previous article on file renaming with Python .

It is important to note that pathlib has greater portability between operating systems and is therefore preferred.

Use write_text()

We can use the Path().write_text() method from pathlib to write text to a file.

First, we use the Path class from pathlib to access file.txt , and second, we call the write_text() method to append text to the file. Let’s run an example:

Next, we'll use the is_file() , with_name() and with_suffix() functions to filter the files we want to update. We will only update those files that fulfill certain conditions.

The is_file() function will return a Boolean value that’s True if the path points to a regular file and False if it does not. The with_name() function will return a new path with the changed filename. Finally, with_suffix() will create a new path with a new file extension.

You can read about the details of these methods in the Python documentation .

Let’s run an example that demonstrates all this. We will open our text file, write some text, rename the file, and save it as a CSV file.

File Manipulation in Python

In this final part, we will explore file manipulation in Python using the tell() and seek() methods.

Use tell() to Get the Current Position

The tell() method can be used to get the current position of the file handle in the file.

It helps to determine from where data will be read or written in the file in terms of bytes from the beginning of the file.

You can think of the file handle as a cursor that defines where the data is read or written in the file. This method takes no parameter and returns an integer.

You can find more information in the Python documentation .

Use seek() to Change Stream Positions

The seek() method is used to change the stream position. A stream is a sequence of data elements made available over time, and the stream position refers to the position of the pointer in the file.

The seek() method is useful if you need to read or write from a specific portion of the file. The syntax is:

fp.seek(offset, whence)

What does this mean?

  • fp is the file pointer.
  • offset is the number of positions you want to move. It can be a positive (going forwards) or negative (going backwards) number.
  • 0: The beginning of the file.
  • 1: The current position in the file.
  • 2: The end of the file.

If you omit the whence parameter, the default value is 0.

When we open the file, the position is the beginning of the file. As we work with it, the position advances.

The seek() function is useful when we need to walk along an open file. Let’s run a quick example:

You can find more information in the Python documentation.

Learn More About Working with Files in Python

We covered a lot of ground in this article. You’re getting some solid knowledge about file manipulation with Python.

Now you know how to write to a file in Python and how to write data to a file in Python. We also briefly explored the tell() and seek() methods to manipulate a file.

Don’t forget to check our course on Working with Files and Directories in Python to deepen and solidify your Python knowledge!

You may also like

file write arguments python

How Do You Write a SELECT Statement in SQL?

file write arguments python

What Is a Foreign Key in SQL?

file write arguments python

Enumerate and Explain All the Basic Elements of an SQL Query

Python Tutorial

  • Python Basics
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators
  • Python - Assignment Operators
  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python Control Statements
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Object & Classes
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Built-in Exceptions
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - GUIs
  • Python Questions and Answers
  • Python Useful Resources
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python - Programming Examples
  • Python - Quick Guide
  • Python - Useful Resources
  • Python - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Python File write() Method

Description.

Python file method write() writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called.

Following is the syntax for write() method −

str − This is the String to be written in the file.

Return Value

This method does not return any value.

The following example shows the usage of write() method.

When we run above program, it produces following result −

Read, write, and create files in Python (with and open())

In Python, the open() function allows you to read a file as a string or list, and create, overwrite, or append a file.

Encoding specification: encoding

Open a file for reading: mode='r', read the entire file as a string: read(), read the entire file as a list: readlines(), read a file line by line: readline(), open a file for writing: mode='w', write a string: write(), write a list: writelines(), create an empty file: pass, open a file for exclusive creation: mode='x', check if the file exists before opening, open a file for appending: mode='a', insert at the beginning or in the middle, read and write binary files, read and write files with open() and with.

For both reading and writing scenarios, use the built-in open() function to open the file.

  • Built-in Functions - open() — Python 3.11.3 documentation

The file object, indicated by the path string specified in the first argument, is opened. Use the mode argument to specify read or write, text or binary. Details are described below.

Paths can be either absolute or relative to the current directory. You can check the current directory with os.getcwd() and change it with os.chdir() .

  • Get and change the current working directory in Python

Text files are read as io.TextIOWrapper object.

As shown in the example above, you need to close the file object using the close() method. Alternatively, a with block automatically closes the file when the block ends, providing a more convenient approach.

You can use any variable name for the xxx in with open() as xxx: . It represents a file object opened with open() , named xxx , and used within the block. While f is commonly used, other names are also acceptable.

Specify the encoding for reading or writing text files with the encoding argument of open() . The encoding string can be in uppercase or lowercase and can use either a hyphen - or an underscore _ . For example, both 'UTF-8' and 'utf_8' are allowed.

Refer to the official documentation for the encodings supported by Python.

  • codecs - Standard Encodings — Codec registry and base classes — Python 3.11.3 documentation

The default value of encoding depends on the platform. You can check it with locale.getpreferredencoding() .

Read text files

To open a file for reading, set the mode argument of open() to 'r' . The default value for the mode argument is 'r' , so you can omit it. In the following examples, it is omitted.

If you specify a non-existent path in mode='r' , you will get an error ( FileNotFoundError ).

To read the entire file into a single string, use the read() method on the file object.

Although the file object is closed at the end of the with block, the assigned variable remains accessible outside the block.

To read the entire file as a list of lines, use the readlines() method. All lines except the last one include a newline character \n at the end.

If you want to remove the trailing newline character, you can use a list comprehension and call rstrip() on each element.

  • Remove a part of a string (substring) in Python
  • List comprehensions in Python

When iterating over the file object with a for loop, you can retrieve each line as a string (including the newline character at the end). Here, repr() is used to display the newline character as is.

  • Built-in Functions - repr() — Python 3.11.3 documentation

To read one line at a time, use next() . An error occurs if there are no more lines to read.

  • Built-in Functions - next() — Python 3.11.3 documentation

The readline() method of the file object can also retrieve one line at a time, but it does not raise an error after EOF (end of file) and continues to return an empty string '' .

Write text files

To open a file for writing, set the mode argument of open() to 'w' . The file's contents will be overwritten if it exists, or a new file will be created if it does not.

Be careful not to specify a non-existent directory for the new file, as this will result in an error ( FileNotFoundError ).

To write a string to a file, use the write() method on the file object.

Strings containing newline characters are written without any modification.

For more information on strings with line breaks, see the following article:

  • Handle line breaks (newlines) in strings in Python

The write() method only accepts strings as arguments. Passing a different type, such as an integer ( int ) or a floating-point number ( float ), will result in a TypeError . To write a non-string value, convert it to a string using str() before passing it to write() .

To write a list of strings to a file, use the writelines() method. Note that this method does not automatically insert line breaks.

To write each element of the list on a separate line, create a string containing newline characters by using the join() method.

  • Concatenate strings in Python (+ operator, join, etc.)

The writelines() method only accepts lists containing strings as elements. If you want to write a list with elements of other types, such as integers ( int ) or floating-point numbers ( float ), you need to convert the list to a list of strings. See the following article:

  • Convert a list of strings and a list of numbers to each other in Python

To create an empty file, open a new file in write mode ( mode='w' ) without writing any content.

Since the with block requires some statement to be written, use the pass statement, which does nothing.

  • The pass statement in Python

Create a file only if it doesn't exist

Using mode='w' can accidentally overwrite an existing file.

To write to a file only if it doesn't exist, i.e., create a new file without overwriting, you can use one of the following two methods:

To create a new file only if it does not already exist, set the mode argument of open() to 'x' . If the specified file exists, a FileExistsError will be raised.

By using try and except for exception handling, you can create a new file if it doesn't exist and take no action if it already exists.

  • Exception handling in Python (try, except, else, finally)

Use the os.path.isfile() function from the os.path module in the standard library to check if a file exists.

  • Check if a file or a directory exists in Python

Append to a file

To open a file for appending, set the mode argument of open() to 'a' .

write() and writelines() will append to the end of an existing file.

If you want to add a final line, include the newline character when appending.

Note that if the file does not exist, it will be created as a new file, just like when mode='w' is used.

When the mode argument of open() is set to 'r+' , the file is opened in update mode.

write() and writelines() will overwrite the existing file from the beginning.

In the example above, One\nTwo is overwritten by 12345 from the beginning, resulting in 12345wo . The \n is treated as one character.

You can also move the position by using the seek() method of the file object, but you need to specify the position in characters, not lines. This will also overwrite.

readlines() and insert()

If the text file is not huge, it is easier to read the entire file as a list using readlines() and process it. The insert() method of the list allows you to insert new strings at the beginning or in the middle of the lines.

Read the file as a list with readlines() , insert an element using insert() , and then write the updated list using writelines() .

You can specify the number of lines to insert in the first argument of insert() .

For adding, inserting, and removing elements to a list, see the following articles:

  • Add an item to a list in Python (append, extend, insert)
  • Remove an item from a list in Python (clear, pop, remove, del)

Adding a b to the end of the mode argument enables reading and writing binary files. For example, mode='rb' is for reading binary files, and mode='ab' is for appending to the end of binary files.

Like text files, binary files also support read() , readline() , readlines() , write() , and writelines() as methods of the file object.

To open, process, and save image files, use libraries such as Pillow or OpenCV.

  • How to use Pillow (PIL: Python Imaging Library)
  • Reading and saving image files with Python, OpenCV (imread, imwrite)

Related Categories

Related articles.

  • Get a list of file and directory names in Python
  • Check if a file/directory exists in Python (os.path.exists, isfile, isdir)
  • Delete a file/directory in Python (os.remove, shutil.rmtree)
  • Get the file/directory size in Python (os.path.getsize)
  • Zip and unzip files with zipfile and shutil in Python
  • Get the path of the current file (script) in Python: __file__
  • Copy a file/directory in Python (shutil.copy, shutil.copytree)
  • Create a directory with mkdir(), makedirs() in Python
  • Move a file/directory in Python (shutil.move)
  • Get the filename, directory, extension from a path string in Python
  • How to use pathlib in Python
  • How to use glob() in Python
  • Set operations on multiple dictionary keys in Python
  • Remove an item from a dictionary in Python (clear, pop, popitem, del)

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Write function in python.

' src=

Last Updated on November 1, 2023 by Ankit Kochar

file write arguments python

Python stands as a highly favored programming language employed by developers worldwide, celebrated for its user-friendly and straightforward nature, rendering it suitable for both novices and seasoned professionals. Within Python’s extensive toolkit, the "write" function emerges as an indispensable tool, designed to facilitate the process of saving data to a file. In the following discourse, we shall delve into the nuances of Python’s write function, exploring its syntax, available parameters, return value, and offering illustrative examples.

What is a Write() Function in Python?

Within Python, the write() function represents an integral built-in utility for the purpose of recording information to a file. This function accepts a string as its input and proceeds to inscribe the provided string into the designated file. Remarkably adaptable, the write() function exhibits the capability to inscribe an extensive array of data types into a file, encompassing text, numeric values, and even binary data.

To use the write() function, you first need to open the file that you want to write to using the open() function. You can then call the write() function on the file object to write your data to the file. By default, the data will be written to the end of the file, but you can use the seek() function to move the file pointer to a specific location if you need to write data at a particular position in the file.

When working with the write() function, it’s important to be mindful of error handling. Writing to a file can sometimes fail due to reasons such as insufficient disk space, read-only file permissions, or other issues. To avoid data loss or corruption, it’s a good idea to handle any errors that may occur while writing to the file.

Overall, the write() function is a powerful and useful tool for working with files in Python. Whether you’re writing a small text file or a large binary file, the write() function provides a simple and efficient way to write data to a file.

Syntax of Write Function in Python

The syntax of the write function in Python is as follows:

Here, the file is the file object that you want to write to, and str is the string or data that you want to write to the file.

The write() function takes a single argument, which is the string or data that you want to write to the file. This argument must be a string type, or an object that can be converted to a string.

Parameters of Write Function in Python

In Python, the write function requires a solitary argument, namely the string or data you intend to append to the file. This argument necessitates being of string type or an object amenable to conversion into a string representation. It’s important to note that the write() function does not automatically add a newline character at the end of the string. If you want to write multiple lines to a file, you need to add the newline character ("\n") at the end of each line.

Return Value of Write Function in Python

The write function in Python returns the number of characters that were written to the file. This value represents the number of bytes that were written to the file, which may be different from the number of characters in the string that was passed as an argument to the function.

Here’s an example of how you can use the write() function to write a string to a file and then print the number of bytes that were written:

Explanation: In this example, we first open a file named "example.txt" in write mode using the open() function. We then call the write() function to write the string "Hello, PrepBytes!" to the file. The write() function returns the number of bytes that were written to the file, which we store in the num_bytes_written variable. Finally, we print the value of num_bytes_written to the console.

Note that if the file already exists, the write() function will overwrite the existing contents of the file. If you want to append data to the end of the file instead of overwriting it, you can open the file in append mode by passing the "a" mode flag to the open() function instead of "w".

Examples of Write Function in Python

Here are some examples of using the write function in Python:

Example – 1 Writing to a text file Here is an example of how to write to a text file using write function in python

Code Implementation:

Explanation: In this code, we first open a file named "example.txt" in write mode using the open() function. We then call the write() function on the file object to write the string "Hello, PrepBytes!" to the file. Finally, we close the file using the close() function to ensure that any buffered data is written to the file before we exit the program.

Example – 2 Writing multiple lines to a text file Here is an example of how to write multiple lines to a text file.

Explanation: In this example, we first open a file named "example.txt" in write mode using the open() function. We then call the write() function multiple times to write each line of text to the file, adding the newline character ("\n") at the end of each line. Finally, we close the file using the close() function.

Example – 3 Writing to a binary file Here is an example of how to write to a binary file using the write function in python.

Explanation: In this example, we open a file named example.bin in binary write mode using the open() function with the ‘wb’ mode parameter. We then write the binary sequence b’\x41\x42\x43′ to the file using the write() function. This binary sequence corresponds to the ASCII characters A, B, and C. Finally, we close the file using the close() function.

Time and Space Complexity of Write Function in Python

The time and space complexity of the write function in Python can vary depending on a few factors, such as the size of the data being written and the type of storage device being used.

In general, the time complexity of the write() function is O(n), where n is the number of bytes being written. This means that the function takes longer to write larger amounts of data. The actual time it takes to write the data also depends on the speed of the storage device being used (e.g. a hard drive versus an SSD).

The space complexity of the write() function is O(1), meaning that the amount of memory used by the function is constant, regardless of the size of the data being written. This is because the write() function does not store the data in memory; it simply writes it directly to the storage device.

It’s worth noting that the write() function may also involve some overhead due to operating system calls and disk I/O operations, which can add to the overall time and space complexity of the function. However, these factors are largely outside of the control of the Python interpreter and depend on the specific hardware and operating system being used.

Conclusion The write function in Python is a versatile tool for saving data to files. It primarily accepts strings or objects that can be converted to strings as input and writes them to the specified file. It is a fundamental function for file manipulation in Python and can be used in a wide range of applications, from creating and editing text files to handling binary data.

FAQs related to Write Function in Python

Here are some FAQs related to the write function in Python:

1. What happens if the file I’m trying to write to does not exist? If the specified file does not exist when you open it for writing, Python will create a new file with that name. If the file already exists, its contents will be overwritten unless you use the "a" mode (append mode) instead of "w."

2. Can I write data of different types using the write function? Yes, the write function in Python primarily deals with strings, but you can convert other data types (e.g., numbers) to strings using functions like str() before writing them to a file.

3. What is the difference between "w" and "a" file modes? "w" mode (write mode) overwrites the file if it already exists, while "a" mode (append mode) appends data to the end of the file without overwriting its existing contents.

4. Are there any other file modes for writing in Python? Yes, there are other modes like "wb" for writing binary data, "x" for exclusive creation (fails if the file already exists), and more. You can choose the mode that suits your specific needs.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Python list functions & python list methods, python interview questions, namespaces and scope in python, what is the difference between append and extend in python, python program to check for the perfect square, python program to find the sum of first n natural numbers.

  • Free Python 3 Tutorial
  • Control Flow
  • Exception Handling
  • Python Programs
  • Python Projects
  • Python Interview Questions
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Python program to print the binary value of the numbers from 1 to N
  • How to iterate over files in directory using Python?
  • Python Program to Count Words in Text File
  • How to Convert PIL Image into pygame surface image?
  • Python program to capitalize the first letter of every word in the file
  • Python program to print number of bits to store an integer and also the number in Binary format
  • Python Program to Print Lines Containing Given String in File
  • How to search and replace text in a file in Python ?
  • Python Program to Replace Text in a File
  • Python Program for Sum the digits of a given number
  • Python Program That Prints Out the Decimal Equivalents of 1/2, 1/3, 1/4, . . . ,1/10
  • How to read multiple text files from folder in Python?
  • Python Program to Flatten a List without using Recursion
  • Python - Lambda Function to Check if value is in a List
  • Convert "unknown format" strings to datetime objects in Python
  • How to Get the Number of Elements in a Python List?
  • How to inverse a matrix using NumPy
  • Python program to Reverse a single line of a text file
  • How to get size of folder using Python?

Write Multiple Variables to a File using Python

Storing multiple variables in a file is a common task in programming, especially when dealing with data persistence or configuration settings. In this article, we will explore three different approaches to efficiently writing multiple variables in a file using Python.

Write Multiple Variables To A File in Python

Below are the possible approaches to writing multiple variables to a file in Python .

  • Using the repr() function
  • Using the string formatting
  • Using the str() function

Write Multiple Variables To A File Using the repr() function

In this approach we are using the repr() function to convert each variable into its string representation, preserving its data type, and write them to a file named ‘ output.txt ‘ in the format of variable assignments, allowing for easy reconstruction of the variables when read back from the file.

Write Multiple Variables To A File Using the string formatting

In this approach, we are using string formatting to write multiple variables (website_name, founded_year, and is_popular) to a file named ‘ output.txt’ , creating a clear and human-readable representation of the data with formatted labels and values.

Write Multiple Variables To A File Using the str() function

In this approach, we are using the str() function to convert each variabl e (website_name, founded_year, and is_popular) into strings and writes them to a file named ‘ output.txt’ , presenting a proper representation of the variables with labeled values.

Please Login to comment...

  • Python file-handling-programs
  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autopep8 argument didn't works #256

@bagustris

bagustris commented Mar 29, 2024 • edited

@github-actions

karthiknadig commented Mar 29, 2024 • edited

Sorry, something went wrong.

@karthiknadig

bagustris commented Apr 1, 2024

No branches or pull requests

@bagustris

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python file open.

File handling is an important part of any web application.

Python has several functions for creating, reading, updating, and deleting files.

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename , and mode .

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

To open a file for reading it is enough to specify the name of the file:

The code above is the same as:

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error.

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

VIDEO

  1. File Manipulation In Python

  2. Create folders & Read / Write a file using Python

  3. Write to a Text File in Python

  4. File Handling in Python (Writing to text files in Python)

  5. The readlines & writelines Functions in Python

  6. python file handling, file modes, built in methods , create, write, read, append and delete a file

COMMENTS

  1. python

    Notice that the substitution variables x, y, z are all in parentheses, which means they are a single tuple passed to the % operator. In your code, notice how you have four parameters to the write () function (I've put each parameter on a separate line to make it easier to see): f.write(. "add unit at-wc 0 0 0 %s" % x, y, z, "0.000 0.000 0.000 ...

  2. Using .write function with multiple arguments for writing to a txt file

    6. Python offers many solutions to this problem. You can combine your arguments to make a single string using several methods: Convert to string and concatenate. out_write.write (str (labels [arr]) + " " + str (results [arr]) + "\n") Old-school string interpolation using %. out_write.write ("%s %s\n" % (labels [arr], results [arr]))

  3. Python File Write

    Write to an Existing File. To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content

  4. Reading and Writing Files in Python (Guide)

    Let's say you wanted to access the cats.gif file, and your current location was in the same folder as path.In order to access the file, you need to go through the path folder and then the to folder, finally arriving at the cats.gif file. The Folder Path is path/to/.The File Name is cats.The File Extension is .gif.So the full path is path/to/cats.gif. ...

  5. 7. Input and Output

    The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.

  6. Python Write to File

    🔹 How to Delete Files . To remove a file using Python, you need to import a module called os which contains functions that interact with your operating system. 💡 Tip: A module is a Python file with related variables, functions, and classes. Particularly, you need the remove() function. This function takes the path to the file as argument ...

  7. Python Read And Write File: With Examples • Python Land Tutorial

    Open a file in Python. In Python, we open a file with the open() function. It's part of Python's built-in functions, you don't need to import anything to use open(). The open() function expects at least one argument: the file name. If the file was successfully opened, it returns a file object that you can use to read from and write to ...

  8. How to Write to File in Python

    When you want to write data to a file in Python, you'll probably want to add one or more rows at once. The data can be stored in lists or a dictionary. Let's explore some ways to write data to files in Python. Writing List Data to a CSV. Let's explore how to add a single row of data with writerow() and multiple rows of data with writerows().

  9. How to Write to Text File in Python

    To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method. The following shows the basic syntax of the open() function:

  10. Python File write() Method

    Python file method write() writes a string str to the file. There is no return value. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called. Syntax. Following is the syntax for write() method −. fileObject.write( str ) Parameters. str − This is the String to be written in the file ...

  11. Writing to file in Python

    To write to a file in Python using a for statement, you can follow these steps: Open the file using the open () function with the appropriate mode ('w' for writing). Use the for statement to loop over the data you want to write to the file. Use the file object's write () method to write the data to the file.

  12. Read, write, and create files in Python (with and open())

    Read a file line by line: readline() Write text files. Open a file for writing: mode='w'. Write a string: write() Write a list: writelines() Create an empty file: pass. Create a file only if it doesn't exist. Open a file for exclusive creation: mode='x'. Check if the file exists before opening.

  13. Write() Function in Python

    The syntax of the write function in Python is as follows: file.write(str) Here, the file is the file object that you want to write to, and str is the string or data that you want to write to the file. The write() function takes a single argument, which is the string or data that you want to write to the file. This argument must be a string type ...

  14. Python Command-Line Arguments

    The arguments Python, Command, Line, and Arguments are the remaining elements in the list. With this short introduction into a few arcane aspects of the C language, you're now armed with some valuable knowledge to further grasp Python command-line arguments. ... For more information about handling file content, check out Reading and Writing ...

  15. Write Multiple Variables to a File using Python

    Using the repr() function; Using the string formatting; Using the str() function; Write Multiple Variables To A File Using the repr() function. In this approach we are using the repr() function to convert each variable into its string representation, preserving its data type, and write them to a file named ' output.txt ' in the format of variable assignments, allowing for easy ...

  16. Your Guide to the Python print() Function

    As you can see, these predefined values resemble file-like objects with mode and encoding attributes as well as .read() and .write() methods among many others. By default, print() is bound to sys.stdout through its file argument, but you can change that. Use that keyword argument to indicate a file that was open in write or append mode, so that ...

  17. Python File write() Method

    Definition and Usage. The write() method writes a specified text to the file. Where the specified text will be inserted depends on the file mode and stream position. "a" : The text will be inserted at the current file stream position, default at the end of the file. "w": The file will be emptied before the text will be inserted at the current ...

  18. Autopep8 argument didn't works #256

    The extension does not support using—in-place.This is by design. This is to support formatting unsaved files and notebook cells. if you want to format on save, the content is not on disk yet.

  19. Reading and Writing WAV Files in Python

    There's an abundance of third-party tools and libraries for manipulating and analyzing audio WAV files in Python. At the same time, the language ships with the little-known wave module in its standard library, offering a quick and straightforward way to read and write such files. Knowing Python's wave module can help you dip your toes into digital audio processing.

  20. parameters

    The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

  21. Python File Open

    The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: ... file does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "w" - Write - Opens a file for writing ...

  22. python

    The script can also be executed on a Windows computer in a Command Prompt as shown below and the results will be printed to standard output (be sure the current directory includes the test.py file): D:\scripts>python test.py "D:\data" "20220518" "XYZ123" "D:\logs". test process starting at 20220518 17:20.