Python create file and write to file

How to Create (Write) Text File in Python

In Python, there is no need for importing external library to read and write files. Python provides an inbuilt function for creating, writing, and reading files.

How to Open a Text File in Python

To open a file, you need to use the built-in open function. The Python file open function returns a file object that contains methods and attributes to perform various operations for opening files in Python.

Syntax of Python open file function

file_object = open("filename", "mode")
  • filename: gives name of the file that the file object has opened.
  • mode: attribute of a file object tells you which mode a file was opened in.

More details of these modes are explained below

How to Create a Text File in Python

With Write to file Python, you can create a .text files (guru99.txt) by using the code, we have demonstrated here:

Step 1) Open the .txt file

  • We declared the variable “f” to open a file named guru99.txt. Open takes 2 arguments, the file that we want to open and a string that represents the kinds of permission or operation we want to do on the file
  • Here, we used “w” letter in our argument, which indicates Python write to file and it will create file in Python if it does not exist in library
  • Plus sign indicates both read and write for Python create file operation.
Читайте также:  Прогноз нейронные сети python

Step 2) Enter data into the file

for i in range(10): f.write("This is line %d\r\n" % (i+1))
  • We have a for loop that runs over a range of 10 numbers.
  • Using the write function to enter data into the file.
  • The output we want to iterate in the file is “this is line number”, which we declare with Python write file function and then percent d (displays integer)
  • So basically we are putting in the line number that we are writing, then putting it in a carriage return and a new line character

Step 3) Close the file instance

Here is the result after code execution for create text file in Python example:

Create a Text File in Python

When you click on your text file in our case “guru99.txt” it will look something like this

Create a Text File in Python

How to Append Text File in Python

You can also append/add a new text to the already existing file or a new file.

Once again if you could see a plus sign in the code, it indicates that it will create a new file if it does not exist. But in our case we already have the file, so we are not required to create a new file for Python append to file operation.

for i in range(2): f.write("Appended line %d\r\n" % (i+1))

This will write data into the file in append mode.

Append Text File in Python

You can see the output in “guru99.txt” file. The output of the code is that earlier file is appended with new data by Python append to file operation.

Append Text File in Python

How to Read Files in Python

You can read a file in Python by calling .txt file in a “read mode”(r).

Step 1) Open the file in Read mode

Step 2) We use the mode function in the code to check that the file is in open mode. If yes, we proceed ahead

Step 3) Use f.read to read file data and store it in variable content for reading files in Python

Step 4) Print contents for Python read text file

Here is the output of the read file Python example:

Read Files in Python

How to Read a File line by line in Python

You can also read your .txt file line by line if your data is too big to read. readlines() code will segregate your data in easy to read mode.

Read a File line by line in Python

When you run the code (f1=f.readlines()) to read file line by line in Python, it will separate each line and present the file in a readable format. In our case the line is short and readable, the output will look similar to the read mode. But if there is a complex data file which is not readable, this piece of code could be useful.

File Modes in Python

Following are the various File Modes in Python:

Mode Description
‘r’ This is the default mode. It Opens file for reading.
‘w’ This Mode Opens file for writing.
If file does not exist, it creates a new file.
If file exists it truncates the file.
‘x’ Creates a new file. If file already exists, the operation fails.
‘a’ Open file in append mode.
If file does not exist, it creates a new file.
‘t’ This is the default mode. It opens in text mode.
‘b’ This opens in binary mode.
‘+’ This will open a file for reading and writing (updating)

Here is the complete code for Python print() to File Example

Python 2 Example

def main(): f= open("guru99.txt","w+") #f=open("guru99.txt","a+") for i in range(10): f.write("This is line %d\r\n" % (i+1)) f.close() #Open the file back and read the contents #f=open("guru99.txt", "r") # if f.mode == 'r': # contents =f.read() # print contents #or, readlines reads the individual line into a list #fl =f.readlines() #for x in fl: #print x if __name__== "__main__": main()

Python 3 Example

Below is another Python print() to File Example:

def main(): f= open("guru99.txt","w+") #f=open("guru99.txt","a+") for i in range(10): f.write("This is line %d\r\n" % (i+1)) f.close() #Open the file back and read the contents #f=open("guru99.txt", "r") #if f.mode == 'r': # contents =f.read() # print (contents) #or, readlines reads the individual line into a list #fl =f.readlines() #for x in fl: #print(x) if __name__== "__main__": main()

Summary

  • Python allows you to read, write and delete files
  • Use the function open(“filename”,”w+”) for Python create text file. The + tells the python interpreter for Python open text file with read and write permissions.
  • To append data to an existing file or Python print to file operation, use the command open(“Filename”, “a“)
  • Use the Python read from file function to read the ENTIRE contents of a file
  • Use the readlines function to read the content of the file one by one.

Источник

Create File in Python

In this tutorial, you’ll learn how to create a file in Python.

Python is widely used in data analytics and comes with some inbuilt functions to work with files. We can create a file and do different operations, such as write a file and read a file using Python.

After reading this tutorial, you’ll learn: –

  • Create a file in the current directory or a specified directory
  • Create a file if not exists
  • Create a file with a date and time as its name
  • Create a file with permissions

Table of contents

Create A Empty Text File

We don’t have to import any module to create a new file. We can create a file using the built-in function open() .

open('file_Path', 'access_mode')

Pass the file name and access mode to the open() function to create a file. Access mode specifies the purpose of opening a file.

Below is the list of access modes for creating an a file.

created files

  • The file is created in the same directory where our program/script is running.
  • If you have not specified any specific path(directory location), the file is created in the working directory. It is known as creating a file using the relative path. A relative path contains the current directory and then the file name.

You can verify the result using the following four approaches

  1. If the script executed without an error or exception
  2. By checking the working directory manually to look for a new file
  3. Use the os.listdir(directory_path) function to list all files from a folder before and after creating a file
  4. Use the os.path.isfile(file_path) function to verify if a newly created file exists in a directory.

Let’s verify our operation result.

import os # list files from a working directory print(os.listdir()) # verify file exist print(os.path.isfile('sales.txt'))
['sample.txt', 'sales.txt', 'sales_2.txt'] True

Create File In A Specific Directory

To create a file inside a specific directory, we need to open a file using the absolute path. An absolute path contains the entire path to the file or directory that we need to use.

It includes the complete directory list required to locate the file. For example, /user/Pynative/data/sales.txt is an absolute path to discover the sales.txt . All of the information needed to find the file is contained in the path string.

Let’s see the example to create a file for writing using the absolute path.

# create a text file for writing with open(r'E:\pynative\reports\profit.txt', 'w') as fp: fp.write('This is first line') pass 

Note: Using the with statement a file is closed automatically it ensures that all the resources that are tied up with the file are released.

Let’s verify result using the absolute path.

import os # list files a directory print(os.listdir(r'E:\pynative\reports')) # output ['sample.txt', 'sales.txt', 'sales_2.txt' 'profit.txt'] # verify file exist print(os.path.isfile(r'E:\pynative\reports\profit.txt')) # output True

Also, you can join directory path and file name to create file at the specified location.

If you have a directory path and file name in two variables, use the os.path.join() function to construct a full path. This function accepts the directory path and file name as arguments and constructs an absolute path to create a file.

import os # Specify the directory path path = r'E:\pynative\account' file_name = 'revenue.txt' # Creating a file at specified folder # join directory and file path with open(os.path.join(path, file_name), 'w') as fp: # uncomment below line if you want to create an empty file fp.write('This is a new line')

Create a File If Not Exists

Sometimes it is essential not to create a new file if a file with the same name already exists in a given path. By default, when you open a file in write mode, it overwrites it if it exists. Else, create the new one.

We can create a file only if it is not present using the following two ways:

  • Use os.path.exists(«file_path») function to check if a file exists.
  • Use the access mode x in the open() function and exception handling.

Example 1: create file if not exists.

import os file_path = r'E:\pynative\account\profit.txt' if os.path.exists(file_path): print('file already exists') else: # create a file with open(file_path, 'w') as fp: # uncomment if you want empty file fp.write('This is first line')

Example 2: Use file access mode x

The access mode x open a file for exclusive creation. If the file already exists, this operation fails with FileExistsError . Use try-except block to handle this error.

try: file_path = r'E:\pynative\account\profit.txt' # create file with open(file_path, 'x') as fp: pass except: print('File already exists') 

Create File with a DateTime

Let’s see how to create a text file with the current date as its name. Use the datetime module to get the current date and time and assign it to the file name to create a file with the date and time in its name.

  • Python provides a datetime module that has several classes to access and manipulate the date and timestamp value.
  • First, get the current datetime value
  • Next, we need to format datetime into a string to use it as a file name.
  • At last, pass it to the open() function to create a file
from datetime import datetime # get current date and time x = datetime.now() # create a file with date as a name day-month-year file_name = x.strftime('%d-%m-%Y.txt') with open(file_name, 'w') as fp: print('created', file_name) # with name as day-month-year-hours-minutes-seconds file_name_2 = x.strftime('%d-%m-%Y-%H-%M-%S.txt') with open(file_name_2, 'w') as fp: print('created', file_name_2) # at specified directory file_name_3 = r"E:\demos\files_demos\account\\" + x.strftime('%d-%m-%Y-%H-%M-%S.txt') with open(file_name_3, 'w') as fp: print('created', file_name_3)
created 29-06-2021.txt created 29-06-2021-14-57-24.txt created E:\demos\files_demos\account\\29-06-2021-14-57-24.txt

Create a file with Permission

Let’s see how to create a file with permissions other users can write.

  • To create a file with appropriate permissions, use os.open() to create the file descriptor and set the permission.
  • Next, open the descriptor using the built-in function open()
import os file_path = r'E:\pynative\account\sample.txt' # The default umask is 0o22 which turns off write permission of group and others os.umask(0) with open(os.open(file_path, os.O_CREAT | os.O_WRONLY, 0o777), 'w') as fh: fh.write('content') 

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

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