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
Related
I have the following problem:
I have a folder with files.
I want to write into those files their respective file path + filename (home/text.txt) .
How can I achieve this in python?
Thanks in advance for your time and help!
with open('FOLDER_NAME/FILE_NAME','w+') as f:
Assuming the python file is in the same path as the folder.
You can use:
..
to move back a directory.
file = open("path", "w+")
file.write("string you want to write in there")
file.close
With w+ it is for reading and writing to a file, existing data will be overwritten.
Of course, as Landon said, you can simply do this by using with, which will close the file for you after you are done writing to it:
with open("path") as file:
file.write("same string here")
This second snippet only takes up 2 lines, and it is the common way of opening a file.
However if you want append to instead of overwriting a file, use a+ this will open and allow you to read and append. Which means existing data will still be there, whatever you write will be added to the end. The file will also be created if it doesn’t exist.
Read more:
https://www.geeksforgeeks.org/reading-writing-text-files-python/
Correct way to write line to file?
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'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 a bunch of CSV files with common columns but different rows. I want to merge them all into one CSV file. Here is the script I wrote to do that
import glob, os
os.chdir("./data")
fout = open("merged.csv", "a")
lout = open("merger_log", "a")
for fname in glob.glob("*.csv*"):
with open(fname) as f:
# exclude header for all but the first csv file.
if os.stat("merged.csv").st_size > 0:
next(f)
fout.writelines(f)
log = "Appended %s \n" % fname
print(log)
lout.write(log)
fout.close()
lout.close()
When I run this script, it successfully appends the first few files but gets stuck on one file every time. And by stuck it seems to be adding bits from said file to the output file without moving on to the next file. There's nothing special about the file it stops on, it's about the same size as the rest of them and is not malformed. In fact, I removed that file from the data set and the program hung on a different file. Not sure what is wrong with this script.
If anyone has a better way to merge a bunch of CSV files, I'm all ears.
Thanks!
EDIT: I should mention this script works perfectly fine with just two files.
I have a text file (filenames.txt) which contains over 200 file paths:
/home/chethan/purpose1/script1.txt
/home/chethan/purpose2/script2.txt
/home/chethan/purpose3/script3.txt
/home/chethan/purpose4/script4.txt
Out of the multiple lines present in each of these files, each of them contain a line which is a filename like Reference.txt. My objective is to replace .txt in Reference.txt with .csv in every file. As a beginner of Python I referred to several questions in stackoverflow on similar cases and wrote the following code.
My code:
#! /usr/bin/python
#filename modify_hob.py
import fileinput
f = open('/home/chethan/filenames.txt', 'r')
for i in f.readlines():
for line in fileinput.FileInput(i.strip(),inplace=1):
line = line.replace("txt","csv"),
f.close()
f.close()
When I run my code, the contents of txt files (script1, script2..) mentioned above are wiped away, i.e., they won't be having a single line of text inside them! I am puzzled with this behavior and not able to find out a solution.
This should get you going (untested):
#! /usr/bin/python
#filename modify_hob.py
# Open the file with filenames list.
with open('filenames.txt') as list_f:
# Iterate over the lines, each line represents a file name.
for filename in list_f:
# Rewrite its content.
with open(filename) as f:
content = f.read()
with open(filename, 'w') as f:
f.write(content.replace('.txt', '.csv'))
In your code below, f is set to the open file object of filename.txt and
nothing else. That is what you are closing in both the last two lines.
Also, you are not writing anything back to the files, so you can't expect your
changes to be written back to the disk. (Unless the fileinput module does some
dark magic that I'm missing.)