How can I create a new file in Python?

+2 votes
I am using the file.open() function to create a new file but this does not work. Do I need to pass any arguments or any specific parameters?
Mar 31, 2018 in Python by ana1504.k
• 5,910 points
42 views

2 answers to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
+2 votes
Best answer

You can try the below code which creates the new file with "write" acccess. 

import sys

def WriteFile():

    name = input('Enter name of the file: ')+'.py'  # Enter name of the file along with format

    try:

        file = open(name,'w')   # creates a new file or open one with write access

        file.close()

    except:

        print('error')           # if code doesn't work, print error

        sys.exit(0)

WriteFile()
answered Mar 31, 2018 by anto.trigg4
• 3,420 points

selected Oct 12, 2018 by Omkar
0 votes
import sys

def write():
    print('Creating new text file') 

    name = raw_input('Enter name of text file: ')+'.txt'  # Name of text file coerced with +.txt

    try:
        file = open(name,'a')   # Trying to create a new file or open one
        file.close()

    except:
        print('Something went wrong! Can\'t tell what?')
        sys.exit(0) # quit Python

write()
answered Oct 12, 2018 by findingbugs
• 4,730 points

Related Questions In Python

+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,520 points
54 views
0 votes
1 answer

How can I parse a YAML file in Python?

Read & Write YAML files with Python ...READ MORE

answered Nov 21, 2018 in Python by Nymeria
• 3,500 points
276 views
0 votes
1 answer

How can I read numbers in Python from a custom file?

Hi, good question. Let us first assume that ...READ MORE

answered Feb 6 in Python by Nymeria
• 3,500 points
42 views
0 votes
0 answers

how can i read a text file in python?

can you specify the syntax and prequisites ...READ MORE

Apr 4 in Python by Waseem
• 1,870 points
9 views
+4 votes
6 answers
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 920 points
19 views
+2 votes
6 answers

How can I change directory or "cd" in Python?

Context Manager: cd import os class cd:     """Context manager for ...READ MORE

answered Oct 18, 2018 in Python by Nabarupa
47 views
+4 votes
7 answers

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.