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'])
Related
Context:
I'm creating a program that automatically replaces macOS application icons and I'm currently making a function to backup some information before replacing those icons.
Problem:
When I call the following function one time everything works perfectly but when I call it a second time the same information is appended to the file even though I have provided an if statement.
I can't seem to make the function "read the file and if it doesn't exist create the file then read it" as well as "append to the file if app["app_name"] is not in the file".
Code:
def backup(app_list):
"""
Takes a list of dictionaries containing the "name" & "path" of each application
Saves the original icon name for each application in a file
"""
if not os.path.exists(BACKUP_PATH):
os.mkdir(BACKUP_PATH)
for app in get_icon_name(app_list):
with open(os.path.join(BACKUP_PATH, "CFBundleIconFile.txt"), "a+") as file:
if app["app_name"] not in file.read():
file.write(str(app) + "\n")
Clarification:
The "get_icon_name" function returns a list of dictionaries containing the "app_name" & "icon_name" for each application in the given list.
I was able to solve the problem using the seek() method.
Using file.seek(0) just after opening the file in a+ places the file pointer at the beginning of the file, allowing me to "read the file and if it doesn't exist create the file then read it" .
In order to "append to the file if the statement is True", I added file.seek(0, 2) after the if app["app_name"] not in file.read() statement which places again the file pointer to the end of the file.
Code:
def backup(app_list):
"""
Takes a list of dictionaries containing the "name" & "path" of each application
Saves the original icon name for each application in a file
"""
if not os.path.exists(BACKUP_PATH):
os.mkdir(BACKUP_PATH)
for app in get_icon_name(app_list):
with open(os.path.join(BACKUP_PATH, "CFBundleIconFile.txt"), "a+") as file:
file.seek(0)
if app["app_name"] not in file.read():
file.seek(0, 2)
file.write(str(app) + "\n")
i have written a python script that reads continuously a csv file outputted and updated by a sensor and live plots some data with matplotlib.
Everytime i start recording data from the sensor it creates a new file like:
data-2020_02_27_14_42_29.csv
So everytime i have to update my script to point the correct csv file.
How i can automate this?
Is there a way to recognize the creation of a new file in a specific directory and take the name of it?
with open('/home/matteo/Documents/PlatformIO/Projects/200213-123258-INS/data/data-2020_02_27_14_42_29.csv', 'r') as csv_file:
csv_reader=csv.DictReader(csv_file, delimiter=',')
Thanks
You can get a list of what files there were at the start at end of your script, then get the new item by comparing the two lists.
def read(file):
folder='/home/matteo/Documents/PlatformIO/Projects/200213-123258-INS/data'
start_list=[file for file in os.listdir(folder)]
with open(os.path.join(folder,file), 'r') as csv_file:
csv_reader=csv.DictReader(csv_file, delimiter=',')
#any other code that happens after reading the csv....
end_list=[file for file in os.listdir(folder)]
new_file=list(set(start_list)-set(end_list))
#checks that a new file was found (if nothing new list is empty)
#if it is empty, re-run function on existing file
if new_file!=[]
new_file=new_file[0]
else:
new_file=file
#recursion to call the function on the new file we found
read(new_file)
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 just managed to run my python code on ubuntu, all seems to be going well. My python script writes out a .csv file every hour and I can't seem to find the .csv file.
Having the .csv file is important as I need to do research on the data. I am also using Filezilla, I would have thought the .csv would have run into there.
import csv
import time
collectionTime= datetime.now().strftime('%Y-%m-%d %H:%M:%S')
mylist= [d['Spaces'] for d in data]
mylist.append(collectionTime)
print(mylist)
with open("CarparkData.csv","a",newline="") as f:
writer = csv.writer(f)
writer.writerow(mylist)
In short, your code is outputting to wherever the file you're opening is in this line:
with open("CarparkData.csv","a",newline="") as f:
You can change this filename to the location of wherever you'd like the file to be read/written from/to. For example, data/CarparkData.csv if you had a folder named data/ within your application dedicated to holding data files.
As written in your code, writer.writerow will write the lines to both python's in-memory object of the file (instantiated with open("filename.csv"...), and the file itself (in this case, CarparkData.csv).
The way your code is structured, it won't be creating a new .csv every hour because it is using a static filename. If a file with this name did not exist at time of opening, it will create one, and if it did, it will continue to append new lines to the existing file.
I have two python files, both of them in the same folder. The main file executes the whole function, making my program what I want it to do. The other file writes data to a text file.
However, there's one issue with writing data to the text file: instead of writing each time new lines to the existing text, it completely overwrites the whole file.
File responsible for writing data(writefile.py)
import codecs
def start(text):
codecs.open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'a', 'utf-8')
with open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'w') as file:
file.write(text + '\n')
I've tried out couple of things such as .join(text) or running the code from writefile.py in the main file. Nothing seems to work..
The problem lies with the line
with open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'w') as file:
this one opens the file in write mode, to append you want 'a' option so just change to
with open('D:\\Program Files (x86)\\Python342\\passguess.txt', 'a') as file:
and you should be fine