Create New file using File Dialog - python

How can I create a new file using file dialog with pyqt5?
This is my code so far, it prints out the correct path after I create the new file but it doesn't actually create it
def newFile(self):
name = QtWidgets.QFileDialog.getSaveFileName()
print(name)

The QFileDialog::getSaveFileName() function does not create or save a file as indicated in the docs:
This is a convenience static function that will return a file name selected by the user. The file does not have to exist.
(emphasis mine)
Actually a dialog is created that allows the user to establish the name of a file that the developer must take as a reference to save the information they want, so what you should do is verify the filename is not empty and use it to create the file:
filename, _ = QtWidgets.QFileDialog.getSaveFileName()
if filename:
with open(filename, "w") as f:
# write contents

def newFile(self):
name = QtGui.QFileDialog.getSaveFileName(self, 'Save File')
file = open(name,'w')
text = ""
file.write(text)
file.close()

Related

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.

Upload Excel using web.py

I have tried the following code by slightly modifying the example in documentation
class Upload():
def POST(self):
web.header('enctype','multipart/form-data')
print strftime("%Y-%m-%d %H:%M:%S", gmtime())
x = web.input(file={})
filedir = '/DiginUploads' # change this to the directory you want to store the file in.
if 'file' in x: # to check if the file-object is created
filepath=x.file.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored
fout.write(x.file.file.read()) # writes the uploaded file to the newly created file.
fout.close() # closes the file, upload complete.
But this works only for csv and txt documents. For Excel/pdf etc file gets created but it can't be opened (corrupted). What should I do to handle this scenario?
I saw this but it is about printing the content which does not address my matter.
You need to use wb (binary) mode when opening the file:
fout = open(filedir +'/'+ filename, 'wb')

How to update a '.txt' file with filedialog

How would I be able to create a '.txt' file and store some information from an entry box and be able to update the '.txt' file?
I understand that I would have to use:
file = filedialog.asksaveasfile( mode = 'w', defaultextension = '.txt')
and store the information form the Entrybox into the file:
#the self.nameEntry had the input of 'zack'
name = self.nameEntry.get()
file.write(name)
file.close()
But when the program continues to run and I want to save the new information into the same .txt file, how would I be able to accomplish that without using filedialog.asksaveasfile() all over again? Would I use file = open(file) and then use the file.write()?
I was able to understand how to do it...
Code:
file_name = filedialog.asksaveasfilename(defaultextension = '.txt')
if file_name is None:
return
file = open(file_name, mode 'w')
name = self.nameEntry.get()
file.write(name)
file.close()
Thanks a lot to Kevin for helping me out with my problem :)

Writing to a new file if it doesn't exist, and appending to a file if it does

I have a program which writes a user's highscore to a text file. The file is named by the user when they choose a playername.
If the file with that specific username already exists, then the program should append to the file (so that you can see more than one highscore). And if a file with that username doesn't exist (for example, if the user is new), it should create a new file and write to it.
Here's the relevant, so far not working, code:
try:
with open(player): #player is the varible storing the username input
with open(player, 'a') as highscore:
highscore.write("Username:", player)
except IOError:
with open(player + ".txt", 'w') as highscore:
highscore.write("Username:", player)
The above code creates a new file if it doesn't exist, and writes to it. If it exists, nothing has been appended when I check the file, and I get no errors.
Have you tried mode 'a+'?
with open(filename, 'a+') as f:
f.write(...)
Note however that f.tell() will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.
It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".
import os
player = 'bob'
filename = player+'.txt'
if os.path.exists(filename):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()
Just open it in 'a' mode:
a Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.
with open(filename, 'a') as f:
f.write(...)
To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.
with open('somefile.txt', 'a') as f:
if f.tell() == 0:
print('a new file or the file was empty')
f.write('The header\n')
else:
print('file existed, appending')
f.write('Some data\n')
If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END) right after open or use io.open instead.
Notice that if the file's parent folder doesn't exist you'll get the same error:
IOError: [Errno 2] No such file or directory:
Below is another solution which handles this case:
(*) I used sys.stdout and print instead of f.write just to show another use case
# Make sure the file's folder exist - Create folder if doesn't exist
folder_path = 'path/to/'+folder_name+'/'
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print_to_log_file(folder_path, "Some File" ,"Some Content")
Where the internal print_to_log_file just take care of the file level:
# If you're not familiar with sys.stdout - just ignore it below (just a use case example)
def print_to_log_file(folder_path ,file_name ,content_to_write):
#1) Save a reference to the original standard output
original_stdout = sys.stdout
#2) Choose the mode
write_append_mode = 'a' #Append mode
file_path = folder_path + file_name
if (if not os.path.exists(file_path) ):
write_append_mode = 'w' # Write mode
#3) Perform action on file
with open(file_path, write_append_mode) as f:
sys.stdout = f # Change the standard output to the file we created.
print(file_path, content_to_write)
sys.stdout = original_stdout # Reset the standard output to its original value
Consider the following states:
'w' --> Write to existing file
'w+' --> Write to file, Create it if doesn't exist
'a' --> Append to file
'a+' --> Append to file, Create it if doesn't exist
In your case I would use a different approach and just use 'a' and 'a+'.
Using the pathlib module (python's object-oriented filesystem paths)
Just for kicks, this is perhaps the latest pythonic version of the solution.
from pathlib import Path
path = Path(f'{player}.txt')
path.touch() # default exists_ok=True
with path.open('a') as highscore:
highscore.write(f'Username:{player}')

Save Dialog only appear once?

I am currently making a desktop widget and what I want to do is create a file in which a user can edit and then save. However, if you guys are familiar with Microsoft word or any other text editors, I want it so that after you hit File -> save, a save dialog appears in which you can choose where to save the file and the file's name. However, after the first time, if the file name stays the same, the save dialog will not come up--rather it will just automatically save over what was previously written. This is what I want to implement but I am having trouble trying to do this. Following is my method for saving files using the save dialog but I am unsure on how to save without having the save dialog pop up.
def saveFile(self):
filename = QtGui.QFileDialog.getSaveFileName(None, 'Save File', os.path.expanduser("~/Desktop/Calendar Data/"+self.dateString), ".txt")
f = open(filename, 'w')
filedata = self.text.toPlainText()
f.write(filedata)
f.close()
Anyone have any idea how to do this? If so that would be great! Thanks for helping.
You should make filename an instance attribute, so you can just check if it was already set:
class Spam:
...
def __init__(self):
self.filename = None
def saveFile(self):
if not self.filename:
self.filename = QtGui.QFileDialog.getSaveFileName(...)
# here you should check if the dialog wasn't cancelled
with open(filename, 'w') as f:
f.write(self.text.toPlainText())
...

Categories

Resources