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,870 points
102 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,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,750 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,810 points
161 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,520 points
2,273 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,520 points
77 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
• 4,480 points
26 views
+4 votes
6 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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 282 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
121 views
+4 votes
7 answers