I am currently creating a Python Tkinter program to edit and create .txt files. In doing so, I have created a file opening system using the File Dialog method and have the user selected path saved as: a file variable. I have looped through the file and added it to the text widget via the insert method. I opened a test .txt file with a 2 line content. It simply says: this is a test file. (New line) it is used for test purposes
The problem is that the text widget appears blank
My code is:
from tkinter import *
from tkinter import FileDialog
master = Tk()
#all other code like filedialog opening code is here
editarea = Text(master,height=10,width=25)
editarea.grid(column=0,row=1)
f = open(file,"r")
for x in f:
editarea.insert(END,x)
This code is run in Python 3.7
How do I make the Text widget display the contents of the .txt file and can still be edited?
Many Thanks
(For the future)
I am aware the code above is a bit vage and won't run but you hopefully get the gist of my problem :)
here is a better solution, whole file at once
with open(file, "r") as txtr:
data = txtr.read()
editarea.insert(END, data)
this here is line by line
with open(file, "r") as txtr:
data = txtr.readlines()
for x in data:
editarea.insert(END, x)
if for some strange reason it didn't work, try this:
for x in range(len(data)):
editarea.insert(END, data[x])
Related
I am working in the field of astronomy, and the process that I use to unzip the images that I get from the telescopes can be very tedious. The format that the images come in is 'fits.fz' which stands for fits.fits-zipped. I want to decompress these into just '.fits'. I have already I'm working on a program that simplifies this process of decompressing. I have created a graphical interface with two buttons through Python and Tkinter. The first button creates a text file named 'list.txt' and then executes a pre-existing .bat file which dumps the names of every file in a specific directory that ends with 'fits.fz' into 'list.txt'. The first button is also supposed to copy the specific names of the files into a very specific place in another bat file. The other .bat file is called 'Decompress.bat' and is supposed to use the following command for each file in 'list.txt':
C:\ds9\ds9.exe
C:\directory\FITS FILE HERE
-savefits
I would like for the python program to be able to copy specific sections from a line of code and paste them where 'FITS FILE HERE' is.
The following is the function that is executed when the first button is pressed.
f = open('C:/jah/list.txt')
f1 = open('C:/jah/decompress.bat', 'a')
def begin_wombocombo(): #Is function for first button
open('C:/jah/list.txt', 'w').close() #Clears 'list.txt'
open('C:/jah/decompress.bat', 'w').close() #Clears 'decompress.bat'
subprocess.call([r'C:/jah/newbat.bat']) #Dumps directory into 'list.txt'
doIHaveToCopyTheLine=False #Bool for whether or not the program has to copy line
for line in f.readlines(): #loops through all instances to find fz files and then pastes them into decompress.bat
if 'fits.fz' in line:
doIHaveToCopyTheLine=True
if doIHaveToCopyTheLine:
f1.write(line)
f1.close()
f.close()
The issue with this is that it only copies the lines of text that has the fits.fz files. This means that it copies everything else on the line such as when the file was created. Is there any way to simply copy and paste the fits.fz file alone? How would I go about working these strings into the .bat file?
Thank you for your time, and btw the second button just executes 'decompress.bat' which is the file with the commands to unzip the images.
I think in Python, something like this would do the trick, without writing out batch files etc.
import os
import subprocess
target_directory = 'C:\\directory\\' # change this as required
zipped_files = [x for x in os.listdir(target_directory)
if x.lower().endswith('.fits.fz')]
for filename in zipped_files:
subprocess.call([r'C:\ds9\ds9.exe', os.path.abspath(filename), '-savefits'])
I am using python 3.5, python-docx, and TKinter. Is there any way to be able to type a .txt file name into an entry box and have python insert the contents of that .txt file into a specific place in docx? I know how to get information from Entry boxes in tkinter and how to convert them into a string.
I want to be able to enter someones name (which would also be the name of the text file) into the entry box and have python insert the content of the .txt file.
Thanks
Update here is my code that I'm trying
from tkinter import *
from tkinter import ttk
import tkinter as tk
from docx import Document
root=Tk()
def make_document():
testbox=ProjectEngineerEntry.get()
TestBox=str(testbox)
def projectengineer():
with open(+TestBox+'.txt') as f:
for line in f:
document.add_paragraph(line)
document=Document()
h1=document.add_heading('engineer test',level=1)
h1a=document.add_heading('Project Engineer',level=2)
projectengineer()
document.save('test.docx')
notebook=ttk.Notebook()
notebook.pack(fill=BOTH)
frame1=ttk.Frame(notebook)
notebook.add(frame1,text='Tester',sticky=W)
tester1=Label(frame1,text='Test1')
ProjectEngineerEntry=Entry(frame1)
tester1.pack()
ProjectEngineerEntry.pack()
save=Button(frame1,text='Save',command=make_document).pack()
As you can see I am trying to take the information from the entry box, convert it to a string and then use that string to open a text file with that specific name. However I keep getting
a TypeError: bad operand type for unary +: 'str'
I don't understand whats going on here. In the actual document I used the ++ method when saving the file (saves it as the current date and time).
python-docx doesn't have this functionality and it's unlikely it ever will. Typically this sort of thing is done to suit by the script or application using python-docx. Something like this:
from docx import Document
document = Document()
with open('textfile.txt') as f:
for line in f:
document.add_paragraph(line)
document.save('wordfile.docx')
You'll need to deal with the particulars, like how a paragraph is separated (perhaps a blank line) and so on, but the code doesn't need to be much longer than this.
Take a look at the following python library: https://python-docx.readthedocs.io/en/latest/
just a pretty adaptation from scanny answer
%pip install python-docx
from docx import Document
def to_docx(file_path_plain_text, file_path_docx):
document = Document()
with open(file_path_plain_text) as f:
for line in f:
document.add_paragraph(line)
document.save(file_path_docx)
to_docx('my_file.txt', 'report.docx')
Possible charmap and encoding errors may arise in capturing the content of the plaintext file. But writing a robust function about this capture would not be part of the scope of this topic.
I would like to import some data from a .txt file.
Right now I am doing it like so:
filename = "C:/results/results.txt"
file = open(filename, 'r')
lines = file.readlines()
file.close()
I wondering if there is way to have some dialog box, which will allow picking the right .txt file file, instead of supplying filename variable. Like this:
Is it possible to get this dialog box without some custom python UI module (like tkinter or similar)? Is it possible to get it through System.Windows.Forms for example?
I am using python 2.7.
Thank you for the reply
In this case the path is to use the ironpython, link
I am working on a python program that will prompt the user to select files (.txt) and then write these file names to a text file. I am thinking I am on the right track but this is not working for me and I do not know why. It creates the file list .txt but does not place the filenames into the text document.
import Tkinter, tkFileDialog
root = Tkinter.Tk()
files = tkFileDialog.askopenfilenames(parent = root, title = "Select files...", multiple =1)
SPSSList = open('list.txt', 'w')
SPSSList.write(files)
SPSSList.close()
Sorry if I am missing something obvious and I appreciate any help.
file.write takes a string; askopenfilenames returns a tuple of filenames.
Use
for f in files:
print >> SPSSList, f
if you want to write them each on a separate line. Alternately,
SPSSList.write('\n'.join(files))
is somewhat more flexible since you can choose to use a different separator (e.g. ','.join).
I'm using VBA to save an excel worksheet as a CSV file. The macro saves it as a CSv and then opens it in excel. I have a python code that reads the file, by the user selecting it (using tkinter) to open.
Is there a way to modify my python code to detect an open csv file, so that I can skip the user select stage? I want it to return the filepath or read open csv file. This is the current version of my code, which works if the csv file is open in excel:
import numpy as np
from Tkinter import Tk
from tkFileDialog import askopenfilename
tk=Tk()
tk.withdraw()
filename = askopenfilename()
data = np.genfromtxt(filename, dtype=[('x',float),('y',float)],comments='"', delimiter=',',skip_header=1,missing_values=True)
tk.destroy()
x=data['x']
x = x[np.logical_not(np.isnan(x))]
y=data['y']
y = y[np.logical_not(np.isnan(y))]
print x
print y
Which OS? If it is Windows, take a look at Get name of active Excel workbook from Python. The code in the question itself may do what you're looking for:
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
print(xl.ActiveWorkbook.FullName)
As mentioned in that question's answer, this only prints the path to the most recently opened file, but in your case it sounds like the macro is opening the file, so perhaps it would work? Otherwise, take a look at the actual answer - it seems very complete.