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
Related
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])
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'])
Let me preface by saying I am very new to programming. I'm creating a fun program that I can use to start my day at work. One of the things I want it to do is display a random compliment. I made a text file that has multiple lines in it. How do I store that text file then open it?
I've opened text files before that were on my desktop but I want this one to be embedded in the code so when I compile the program I can take it to any computer.
I've googled a ton of different key words and keep finding the basics of opening and reading txt files but that's not exactly what I need.
Perhaps start with defining a default path to your file; this makes it easier to change the path when moving to another computer. Next, define a function in your program to read and return the contents of the file:
FILE_PATH = "my/path/to/file/"
def read_file(file_name):
with open(FILE_PATH + file_name) as f:
return f.read()
With that in place, you can use this function to read, modify, or display the file contents, for example to edit something from your file:
def edit_comments():
text = read_file("daily_comments.txt")
text = text.replace("foo", "foo2")
return text
There are obviously many ways to approach this task, this is just a simple example to get you started.
I've written a simple python script that takes a .csv file, rearranges it and spits out an excel file. My aim is to be able to right click on a .csv file in Windows and for it to generate an .xslx file. I've used PyInstaller to successfully create an .exe and I've used default programs editor to put my executable in the context menu when csv files are right clicked. What I can't figure out is how to do the I/O correctly.
What I have is :
import fileinput
import csv
try:
csv_filename = fileinput.filename()
print(csv_filename)
except: print('no input')
with open(filename_csv, 'rt', newline='', encoding='utf8') as csvfile:
# do stuff
# write xslx_filename
Which doesn't work.
How do I access the file windows passes me when I open a file?
Edit:
Just to clear up confusion. If I hard code the location of a csv file, my script works just fine. My problem is how do I access the file that Windows (presumably) passes to my script when I right click on a csv file and choose to open with csv2xslx (my script).
Thanks to martineau above for the pointer. The following made it work:
file = sys.argv[1]
with open(file, 'rt', newline='', encoding='utf8') as csvfile:
# do stuff
# write xslx_filename
I'm still not sure if that is the 'correct' way of doing it, but it works so I'm happy.
is there a way to open files without using QFileDialog.getOpenFileName parameter? The thing is, I have a some buttons that upon clicking them, a notepad will pop up in which you can type anything into the notepad. Then, you can save whatever you wrote in that notepad as a text file. What I want to do is, if I click the button again, I will reopen the file that I had previously edited via the notepad and can continue typing where I left off. However, I don't want to use getOpenFileName. Would it be possible to open a file without using this functionality? Below is my attempt but my if statement keeps evaluating to be false. If anyone could help that would be great. Thanks!
#Testing if the file already exists
if(os.path.exists("~/Desktop/" +self.fileName + ".txt")):
f = open(self.fileName + ".txt", 'r')
filedata = f.read()
self.text.setText(filedata)
f.close()
#Opens a new notepad if there wasn't a previous fileconstructed
else:
self.textBox = textBoxWindow(self.fileName)
self.textBox.show()
If you are on Winsows (you said the word Notepad), you can use the subprocess module to open any file with whatever program currently associated with the file type as follows:
import subprocess
self.filename = r'C:\test.txt'
subprocess.call(['start', self.filename], shell=True)
But the shell=True argument is kinda dangerous, especially of the filename comes as an input.
you can use the webbrowser module too, though not supported use of it I guess:
import webbrowser
webbrowser.open(self.filename)