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
• 7,910 points
1,292 views

2 answers to this question.

+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,440 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,780 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,890 points
19,990 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,560 points
10,471 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, 2019 in Python by Nymeria
• 3,560 points
1,119 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, 2019 in Python by Waseem
• 4,540 points
572 views
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,042 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,422 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
28,807 views
+4 votes
7 answers
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP