All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Create A File In Python

Last Updated : Jul 25, 2023

How To Create A File In Python

In this article we will show you the solution of how to create a file in python, the purpose of this tutorial is to show you how to open a file, write to it, and close it. In addition to reading from the file, you will also learn how to use Python to read it.

It is your responsibility to understand the basics of how to use files in Python by the end of this tutorial.

The handling of files is an important aspect of every web application. You can perform different types of activities on an opened file depending on its Access Mode.

These describe how the file will be used after it has been opened. As well as specifying the location of the file handle within the file, these modes also specify the duration of the file.

We will now discuss the idea of how to create a file in python with an example.

Step By Step Guide On How To Create A File In Python :-

def main():
    f= open("tc.txt","w+")
    #f=open("tc.txt","a+")
    for i in range(10):
         f.write("This is line %d\r\n" % (i+1))
    f.close()
    #f=open("tc.txt", "r")
    #if f.mode == 'r':
    # contents =f.read()
    # print (contents)
    #fl =f.readlines()
    #for x in fl:
    #print(x)
if __name__== "__main__":
  main()
  1. A function defined in a program is called Main.
  2. Tc.txt is created in writing mode ("w+") due to the use of the open function within the main function. In the case of a non-existing file or a truncated file, a new file will be created or a truncated file will be created when this command is run.
  3. After that, it uses a for loop to write 10 lines of text to the file, inserting the line number into the text with string formatting.
  4. Closing the file using the close method allows the file to be reopened.
  5. The contents of the file can be read back in and printed as comments on some commented-out lines. If you want to read the entire file as a string, then you can use the read method. If you want to read each line individually, then you can use the readlines method. A commented-out example of each of these methods is included in the code.
  6. Last but not least, if the script is being run as the main program (in which case it is run as "__main__":), the main function will be called.

Conclusion :-

As a result, we have successfully learned how to create a file in python with an example.

The Python programming language supports reading, writing, and deleting files.

In Python, you can create a text file by using the function open("filename","w+"). Python interpreter for Python opens text files with read and write permissions when the + keyword is applied.

I hope this article on how to create a file in python helps you and the steps and method mentioned above are easy to follow and implement.