Error when creating a new text file with python? - python

This function doesn't work and raises an error. Do I need to change any arguments or parameters?
import sys
def write():
print('Creating new text file')
name = input('Enter name of text file: ')+'.txt' # Name of text file coerced with +.txt
try:
file = open(name,'r+') # 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()

If the file does not exists, open(name,'r+') will fail.
You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.
Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.

instead of using try-except blocks, you could use, if else
this will not execute if the file is non-existent,
open(name,'r+')
if os.path.exists('location\filename.txt'):
print "File exists"
else:
open("location\filename.txt", 'w')
'w' creates a file if its non-exis

following script will use to create any kind of file, with user input as extension
import sys
def create():
print("creating new file")
name=raw_input ("enter the name of file:")
extension=raw_input ("enter extension of file:")
try:
name=name+"."+extension
file=open(name,'a')
file.close()
except:
print("error occured")
sys.exit(0)
create()

This works just fine, but instead of
name = input('Enter name of text file: ')+'.txt'
you should use
name = raw_input('Enter name of text file: ')+'.txt'
along with
open(name,'a') or open(name,'w')

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()
this will work promise :)

You can os.system function for simplicity :
import os
os.system("touch filename.extension")
This invokes system terminal to accomplish the task.

You can use open(name, 'a')
However, when you enter filename, use inverted commas on both sides, otherwise ".txt"cannot be added to filename

Related

How do I remove and then open a file for writing in python?

Here is some code.
sbfldr = input('Enter subfolder name: ')
try:
os.remove(os.path.join(sbfldr, 'Report.html'))
except:
print('Remove error. Please close the report file')
exit()
try:
fwrite = open(os.path.join(sbfldr, 'Report.html'),'a')
exit()
except:
print('Open error. Please close the report file')
exit()
The results I expect are
If an old version of 'Report.html' exists, then remove it.
Open a new 'Report.html' for writing.
When I search for this question I get lots of answers (to other questions). This is probably because the answer is very easy, but I just do not understand how to do it.
There's no need to remove the file when you can just empty it. File mode w will "open for writing, truncating the file first", and if the file doesn't exist, it will create it.
sbfldr = input('Enter subfolder name: ')
fname = os.path.join(sbfldr, 'Report.html')
with open(fname, 'w') as fwrite:
pass # Actual code here
BTW this uses a with-statement, which is the best practice for opening files. As well it ignores the bad error handling (bare except) and unnecessary exit() in your program.
Thanks to #furas for mentioning this in the comments
Try the following, using os.path.exists to check if the file exists, and os.remove to remove it if so:
import os
if os.path.exists("Report.html"):
os.remove("Report.html")
with open("Report.html", "w") as f:
pass #do your thing

How can I include file name error handling with this piece of code?

I am required to include some form of error handling when the user inputs the file name such that if they put a file name which is not within the programs directory then it will appear with an error message. This is the code at the moment:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
file = open(filename, "r+")
for lines in file:
board.append(list(map(int,lines.split())))
I'm not sure where to include the try/except as if I include it like this:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
try:
file = open(filename, "r+")
except:
print("Error: File not found")
for lines in file:
board.append(list(map(int,lines.split())))
Then I get the following error:
line 28, in
for lines in file:
NameError: name 'file' is not defined
I know there probably is a very simple solution but I am struggling with wrapping my head around it.
You should include all lines which may occur error under try, so:
board = []
fileinput = input("Please enter your text file name:")
filename = fileinput + ".txt"
try:
file = open(filename, "r+")
for lines in file:
board.append(list(map(int,lines.split())))
except:
print("Error: File not found")
The way you presented, the program try to ignore error and go over, which ends with NameError: name 'file' is not defined
The second problem in your case would be with scope - file is local variable in try and you call it outside of scope.

delete a user defined text from a text file in python

def Delete_con():
contact_to_delete= input("choose name to delete from contact")
to_Delete=list(contact_to_delete)
with open("phonebook1.txt", "r+") as file:
content = file.read()
for line in content:
if not any(line in line for line in to_Delete):
content.write(line)
I get zero error. but the line is not deleted. This function ask the user what name he or she wants to delete from the text file.
This should help.
def Delete_con():
contact_to_delete= input("choose name to delete from contact")
contact_to_delete = contact_to_delete.lower() #Convert input to lower case
with open("phonebook1.txt", "r") as file:
content = file.readlines() #Read lines from text
content = [line for line in content if contact_to_delete not in line.lower()] #Check if user input is in line
with open("phonebook1.txt", "w") as file: #Write back content to text
file.writelines(content)
Assuming that:
you want the user to supply just the name, and not the full 'name:number' pair
your phonebook stores one name:number pair per line
I'd do something like this:
import os
from tempfile import NamedTemporaryFile
def delete_contact():
contact_name = input('Choose name to delete: ')
# You probably want to pass path in as an argument
path = 'phonebook1.txt'
base_dir = os.path.dirname(path)
with open(path) as phonebook, \
NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as tmp:
for line in phonebook:
# rsplit instead of split supports names containing ':'
# if numbers can also contain ':' you need something smarter
name, number = line.rsplit(':', 1)
if name != contact_name:
tmp.write(line)
os.replace(tmp.name, path)
Using a tempfile like this means that if something goes wrong while processing the file you aren't left with a half-written phonebook, you'll still have the original file unchanged. You're also not reading the entire file into memory with this approach.
os.replace() is Python 3.3+ only, if you're using something older you can use os.rename() as long as you're not using Windows.
Here's the tempfile documentation. In this case, you can think of NamedTemporaryFile(mode='w+', dir=base_dir, delete=False) as something like open('tmpfile.txt', mode='w+'). NamedTemporaryFile saves you from having to find a unique name for your tempfile (so that you don't overwrite an existing file). The dir argument creates the tempfile in the same directory as phonebook1.txt which is a good idea because os.replace() can fail when operating across two different filesystems.

Python raw_input for file writing

I have the following code:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open('targetfile' , 'w')
print "What do we write in this file?"
targetfilefound.write("hello this is working!")
targetfilefound.close()
The script I'm creating should be able to write to a file that the user defines via raw_input. The above could be faulty at core, open to suggestions.
Judging by the stuff the script is printing you probably want the user to input what should be printed to the file so:
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
Note: This method will create the new file if it does not exist. If you want to check whether the file exists you can use the os module, something like this:
import os
print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
if os.path.isfile(targetfile) == True:
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "File does not exist, do you want to create it? (Y/n)"
action = raw_input('> ')
if action == 'Y' or action == 'y':
targetfilefound = open(targetfile , 'w')
print "What do we write in this file?"
targetfilefound.write(raw_input())
targetfilefound.close()
else:
print "No action taken"
As pointed out by others, remove the quotes from target file as you have assigned it already to a variable.
But actually instead of writing as code you can use the with open as given below
with open('somefile.txt', 'a') as the_file:
the_file.write('hello this is working!\n')
In the above case, you don't need to do any exception handling while processing the file. When-ever an error occurs the file cursor object is automatically closed and we dont need to explicitly close it. Even it writing to file it success, it will automatically close the file pointer reference.
Explanation of efficient use of with from Pershing Programming blog

How do I take Someone's name in Python and create a file to write to with that name?

I am a bit new to Python, and trying to do something simple I'm sure. I want to ask someone their name as the initial raw_input and then I want that name to be used to create a file. This is so that any additional raw_input taken from that user it gets recorded to that file.
raw_input("What is your name?")
file = open("newfile.txt", "w")
I have the above code that will create a file called newfile.txt, but how can I make it so that the requested name will be used as the file name?
Thank you!
file = open("user.txt", "w")
Following should work -
user_input = raw_input("What is your name?") # Get user's input in a variable
fname = user_input + '.txt' # Generate a filename using that input
f = open(fname, "w") # Create a file with that filename
f.write('')
f.close()
Save the name in a variable and use it :
name = raw_input("What is your name?")
file = open(name+".txt", "w")
...
file.close()
how can I make it so that the requested name will be used as the file name?
Easy, simply take the variable returned by raw_input (the string entered by the user), and pass this into the open function. The string entered by the user will be used to create the filename:
name = raw_input("What is your name?")
file = open(name, "w")
any additional raw_input taken from that user it gets recorded to that file.
Now use the write function to insert any new data from the user into the file:
content = raw_input("Enter file content:")
file.write(content)
file.close()
Another way without putting raw_input's return value to a variable is to use its return value directly.
file = open(raw_input("What is your name?") + '.txt', 'w')

Categories

Resources