from an GUI application designed with tkinter, I wish to save some datas in a file in appending mode. To get the file's name I use asksaveasfilename from filedialog module. Here is the code:
from tkinter.filedialog import asksaveasfilename
def save_file():
file_name = asksaveasfilename()
if file_name:
f = open(file_name, 'a')
contents = tab_chrono.text_area.get(1.0, 'end')
f.write(contents)
f.close()
The problem happens when I select in the dialog an existing file, I got a warning that the file will be overwritten. It is not true since I append in the file.
Is there a way to get rid of this warning ? Or do I have to rewrite a askappendfilename myself ? This is missing in filedialog module.
The asksaveasfilename dialog accepts a confirmoverwrite argument to enable or disable the file existence check.
file_name = asksaveasfilename(confirmoverwrite=False)
This can be found in the Tk manual for tk_getSaveFile but doesn't appear to be documented for tkinter. It was introduced in Tk 8.5.11 so is relatively new in Tk terms (released Nov 2011).
Use the option confirmoverwrite to prevent the message, when selecting an existing file.
import tkFileDialog
import time
class Example():
dlg = tkFileDialog.asksaveasfilename(confirmoverwrite=False)
fname = dlg
if fname != '':
try:
f = open(fname, "rw+")
text = f.read()
print text
except:
f = open(fname, "w")
new_text = time.time()
f.write(str(new_text)+'\n')
f.close()
Edit: Note that I am using f.read() to be able to print the existing text.
You may want to remove the f.read() and subsequent print statement and replace them with a f.seek(0,2) which positions the pointer at the end of the existing file.
The other option is as follows using the append option in the file open, which will create the file if it doesn't already exist:
import tkFileDialog
import time
class Example():
dlg = tkFileDialog.asksaveasfilename(confirmoverwrite=False)
fname = dlg
if fname != '':
f = open(fname, "a")
new_text = time.time()
f.write(str(new_text)+'\n')
f.close()
Related
I would like to make some form of terminal editor for text-based files.
When started, it prints the current content of the file and makes it possible for user to edit in (multiline input). On press of CTRL + E, it should write that multiline input into specific file and close the prompt.
I have tried using this code, but it doesn't seem to work.
from prompt_toolkit import prompt, PromptSession
from prompt_toolkit.lexers import PygmentsLexer
from pygments.lexers.python import PythonLexer
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
file_path = 'output.txt'
file = open(file_path, 'r')
content = file.read()
new_content = None
session = PromptSession()
bindings = KeyBindings()
#bindings.add('c-e')
def _(event):
global new_content
global file_path
file = open(file_path, 'w')
file.write(new_content)
session.app.exit()
def show_prompt():
global new_content
global session
bottom_toolbar = HTML('<b><style background-color="white" color="green">Input</style></b>')
lexer = PygmentsLexer(PythonLexer)
new_content = session.prompt('\n',
default=content,
lexer=lexer,
multiline=True,
bottom_toolbar=bottom_toolbar,
key_bindings=bindings)
# Start of the program
if __name__ == '__main__':
show_prompt()
I have a function similar to this:
def open_tmp():
tmp = mktemp()
copy('file.txt', tmp)
return open(tmp, 'rt')
And I would like to remove automatically the created temporal file when the file will close, for example:
file = open_tmp()
# Do something with file
file.close() # I want to remove the temporal file here
Is it possible? I thought to create a subclass of BaseIO and rewrite the close() function, but I think it is too much work because I would have to rewrite all the BaseIO methods.
You can try this code snippet. As per security concern I recommended to use tempfile instead of your code.
import os
import tempfile
new_file, file_path = tempfile.mkstemp()
try:
with os.fdopen(new_file, 'w') as temp_file:
# Do something with file
temp_file.write('write some dumy text in file')
finally:
os.remove(file_path)
I've found the solution:
import os
import tempfile
def open_tmp():
tmp = tempfile.mkstemp()
copy('file.txt', tmp) # This copy the file.txt to tmp
file = open(tmp, 'rt')
old_close = file.close
def close():
old_close()
os.remove(tmp)
file.close = close
return file
I'm trying to create_python_script function that creates a new python script in the current working directory, adds the line of comments to it declared by the 'comments' variable, and returns the size of the new file. The output I get is 0 but should be 31. Not sure what I'm doing wrong.
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open("program.py", "w") as file:
filesize = os.path.getsize("/home/program.py")
return(filesize)
print(create_python_script("program.py"))
You forgot to actually write to the file, so it won't contain anything. Another important thing to keep in mind, is that the file is closed automatically after the with statement. In other words: nothing is written to the file until the with statement ends, so the file size is still zero in your program.
This should work:
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "w") as f:
f.write(comments)
filesize = os.path.getsize(filename)
return(filesize)
print(create_python_script("program.py"))
Note that the input argument was unused previously and has now been changed.
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, 'w') as file:
filesize = file.write(comments)
return(filesize)
print(create_python_script("program.py"))
There is a rogue indent in the exercise:
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "a") as newprogram:
newprogram.write(comments)
filesize = os.path.getsize(filename)
return(filesize)
print(create_python_script("program.py"))
It should be:
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, "a") as newprogram:
newprogram.write(comments)
filesize = os.path.getsize(filename) #Error over here
return(filesize)
print(create_python_script("program.py"))
I just finished myself.
I'm trying to make a basic script that reads a specified text document, asks for a string of characters to replace and what to replace it, then saves it:
from tkinter import Tk, filedialog
from tkinter.filedialog import askopenfilename
Tk().withdraw()
def OpenFile():
fileName = askopenfilename(initialdir="C:/Users", filetypes = (("Text File", "*.txt"),("All Files","*.*")), title = "Open a document.")
with open(fileName, 'r') as f:
textFile = f.read()
OpenFile()
print(textFile)
There's an error when running the script and selecting a file
Traceback (most recent call last):
File "C:\Users\****\Documents\Python\Find and Replace\replace.py", line 11, in <module>
print(textFile)
NameError: name 'textFile' is not defined
Game on: find what's different:
from tkinter import Tk, filedialog
from tkinter.filedialog import askopenfilename
Tk().withdraw()
def OpenFile():
fileName = askopenfilename(initialdir="C:/Users", filetypes = (("Text File", "*.txt"),("All Files","*.*")), title = "Open a document.")
with open(fileName, 'r') as f:
textFile = f.read()
return textFile # RETURN THE FILE CONTENT HERE SO IT IS VISIBLE TO THE MAIN FUNCTION
textFile = OpenFile() # GET YOUR OUTPUT HERE SO YOU CAN PRINT IT ON THE NEXT LINE
print(textFile)
I would like to have my tkinter program prompt the user to select the path the want to save the file which will be produced by the program.
My code looks like this. At this stage the program only saves to one file (the one I defined to test the program)
What code would I use to have 'test_write.csv' changed to any file the user chooses?
##Writing to .cvs file
with open('test_write.csv', 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
Thank you
Here's an example using tkFileDialog:
import Tkinter
import tkFileDialog
import csv
formats = [('Comma Separated values', '*.csv'), ]
root = Tkinter.Tk()
file_name = tkFileDialog.asksaveasfilename(parent=root, filetypes=formats, title="Save as...")
if file_name:
with open(file_name, 'w') as fp:
a = csv.writer(fp)
# write row of header names
a.writerow(n)
Use the tkFileDialog module.
Example:
import tkFileDialog
with open(tkFileDialog.asksaveasfilename(), "w") as fp:
...
Solution for python3.xxx
import tkinter
from tkinter.filedialog import asksaveasfilename
with open(asksaveasfilename(), 'w') as fp: