Reading a text document and converting it to a string - python

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)

Related

How to merge two pfd files using pypdf2, when one of the files is chosen from a popup window using tkinter

In this first section of code I choose a file from the popup window using tkinter:
# GUI.py
from tkinter.filedialog import askopenfilename
import tkinter as tk
# Create the window and hide it
root = tk.Tk()
root.withdraw()
# Now you are free to popup any dialog that you need
filetypes = (("PDF file", "*.pdf"), ("All files", "*.*"))
filepath = askopenfilename(filetypes=filetypes)
# Now use the filepath
import re
import pdfplumber
import pandas as pd
from collections import namedtuple
lines = []
with pdfplumber.open(filepath) as pdf:
pages = pdf.pages
for page in pdf.pages:
text = page.extract_text()
# print(text)
# Destroy the window
root.destroy()
In this section I merge two selected pdf files together.
I would want to change the code so that the first pdf file (pdf1File) would be the file selected at the beginning from the popup window using tkinter, while the second (pdf2File) would stay the same. How can I do that?
import PyPDF2
# Open the files that have to be merged one by one
pdf1File = open('Fraction_Event_Report.pdf', 'rb')
pdf2File = open('Summary_output.pdf', 'rb')
# Read the files that you have opened
pdf1Reader = PyPDF2.PdfFileReader(pdf1File)
pdf2Reader = PyPDF2.PdfFileReader(pdf2File)
# Create a new PdfFileWriter object which represents a blank PDF document
pdfWriter = PyPDF2.PdfFileWriter()
# Loop through all the pagenumbers for the first document
for pageNum in range(pdf1Reader.numPages):
pageObj = pdf1Reader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Loop through all the pagenumbers for the second document
for pageNum in range(pdf2Reader.numPages):
pageObj = pdf2Reader.getPage(pageNum)
pdfWriter.addPage(pageObj)
# Now that you have copied all the pages in both the documents, write them into the a new document
pdfOutputFile = open('MergedFiles.pdf', 'wb')
pdfWriter.write(pdfOutputFile)
# Close all the files - Created as well as opened
pdfOutputFile.close()
pdf1File.close()
pdf2File.close()

Python Converting String to jpg file

I have a file with strings that were pulled out of our HR system that are images of people that work for our company. I wrote the following code to convert these strings into .jpg files.
d is the name of the new file and x is the image string. I have printed both of these variables and they seem to be working. The file is saving and it is 71KB but when I open it in paint it says that it "cannot read this file and This is not a valid bitmap file, or its format is not currently supported."
I opened it with Photos and it just said it "can't open this file." Are you able to see any issue with the code?
import csv
import base64
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
with open(file_path, 'r') as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
next(readCSV)
for line in readCSV:
d = line[0]
x = line[1]
y = base64.encodebytes(x.encode())
with open("C:\\%s.jpg" %(d), "wb") as fh:
fh.write(base64.decodebytes(y))
fh.close()
break

Get a file name with tkinter.filedialog.asksaveasfilename to append in it

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()

tkinter - retrieve file name during askopenfile

I have a text editor made with Python and tkinter.
This is my 'open file' method:
def onOpen(self):
file = askopenfile(filetypes=[("Text files", "*.txt")])
txt = file.read()
self.text.delete("1.0", END)
root.title(file)
self.text.insert(1.0, txt)
file.close()
I would like to set the window title equal to the file name. At the moment I'm using whatever askopenfile return as the file name, but this returns for example:
<_io.TextIOWrapper name='/Users/user/Desktop/file.txt' mode='r' encoding='UTF-8'>
This, of course, isn't very nice. I would like whatever askopenfilename would return. But if I call askopenfile and askopenfilename the user has to use the 'open file' dialog twice.
Is there any way to retrieve the file name without the second dialog?
If not, does anyone a RegEx to filter out the file name. if you're good with RegEx, the nicest file name would of course be just 'file.txt' not '/Users/user/Desktop/file.txt'. Either way it's fine, though.
You are passing the file object so you see the reference to the file object as the title, you can get the name from the file object with name = root.title(file.name).
If you want just the base name use os.path.basename:
import os
name = os.path.basename(file.name)
from tkinter import *
from tkinter import filedialog as fd
from PIL import ImageTk, Image
import os
def openfile():
filepath= fd.askopenfilename()
onlyfilename = os.path.basename(filepath)
mylabel.config(text=onlyfilename)
myscreen=Tk()
filebutton=Button(text='choose your file',command=openfile)
filebutton.grid(row=0,column=2)
mylabel = Label(myscreen, text="You chossen file path will be displayed here")
mylabel.grid(row=1,column=2)
myscreen.mainloop()

Python CSV.Writer changing saving path

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:

Categories