Python 3 will not read appended data to file - python-3.x

I am trying to write binary data to a file. the program will check first if the file exists. If the file does not exist, the program will create the file and write data into it. While if it does exist the data will be appended to the file. Yet, when ever i try to read the file I cannot read the appanded data only the data written when the file was first created.
def getText(self):
self.readKey()
st = self.inBox.get('1.0', 'end')
fen = Fernet(self.readKey())
encrypted = fen.encrypt(st.encode())
return encrypted
def writeFile(self):
if (os.path.exists('data.txt') == False):
file = open('data.txt',mode='wb' )
file.write(self.getText())
file.close()
else:
file = open('data.txt',mode='ab' )
#sts = file.read()
file.write(self.getText())
file.close()
self.inBox.delete('1.0','end')
def openFile(self):
self.outBox.delete('1.0','end')
fen = Fernet(self.readKey())
try:
f = open("data.txt", mode='rb')
except:
alert_popup(self,'Error','No File Exists')
self.outBox.insert(tk.END, fen.decrypt(f.read()))

Use mode 'a'.
if (os.path.exists('data.txt') == False):
file = open('data.txt',mode='a' )
file.write(self.getText())
file.close()

Related

How to make a duplicate file or copy the contents of stdout file to a new file in Python?

I am using the following way to capture the output of the python script in a file:
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "w")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger("logfile.log")
After the output is logged in a file I am then using using the following method to read from the logfile to write its contents to another file
def read_file():
count = 0
with open('logfile.log', 'r') as firstfile, open('file.txt', 'a') as secondfile:
for line in firstfile:
secondfile.write(line)
The problem I am facing is the output of the log file keeps getting refreshed whenever I try to capture the output. How can I create a duplicate file as I want to search for a string and print its occurrences.
Okay I found the issue I had to open the file and the file mode as r+. So it would be:
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
**self.log = open(filename, "r+")**
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger("logfile.log")

Is there any method to append the value to the list in JSON file (Python)?

My exercise idea is to append new value from the input prompt to the list. Instead of adding new value, my list in JSON file always give the newly inputted value.
import json
file = 'database.json'
namelist = []
name = input("Enter your name:\n")
with open(file, 'w') as file_object:
namelist.append(name)
json.dump(namelist, file_object)
with open('database.json', "r+") as file_object:
data = json.load(file)
# data.update(your_dict) or data.append(new_data)
file.seek(0)
json.dump(data, file)

How do I make my python program to write a new file

I am writing a program by which I can extract data from a file, and then based on some condition, I have to write that data to other files. These files do not exist and only the code will create these new files. I have tried every possible combination of print parameters but nothing is helping. The program seems to run fine with no error in IDLE but no new files are created. Can somebody give me a solution?
Here is my code:
try:
data= open('sketch.txt')
for x in data:
try:
(person, sentence)= x.split(':',1)"""data is in form of sentences with: symbol present"""
man=[] # list to store person
other=[] #list to store sentence
if person=="Man":
man.append(sentence)
elif person=="Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file=open("man_file.txt","w")""" otherman_file and man_file are for storing data"""
otherman_file=open("otherman_file.txt", "w")
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
2 problems
you should use
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
w+ - create file if it doesn't exist and open it in write mode
Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file..
https://docs.python.org/2/library/functions.html
2.
print(man,file= man_file.txt)
print(other, file=otherman_file.txt)
if sketch.txt file do not exist then "man" and "other" will not initialized
and in the print method will throw another exception
try to run this script
def func():
man = [] # list to store person
other = [] # list to store sentence
try:
data = open('sketch.txt', 'r')
for x in data:
try:
(person, sentence) = x.split(':', 1)
if person == "Man":
man.append(sentence)
elif person == "Other Man":
other.append(sentence)
except ValueError:
pass
data.close()
except IOError:
print("file not found")
try:
man_file = open("man_file.txt", "w+")
otherman_file = open("otherman_file.txt", "w+")
# print(man, man_file.txt)
# print(other, otherman_file.txt)
man_file.close()
otherman_file.close()
except IOError:
print ("file error")
func()

Extract attachments from EML files

I currently use this code to Extract attachments from EML files. And I wanted to know if I can link the attachment to mail (EML file). That is, add the eml file name as the attachment name prefix.
So I can know the attachment belongs to what mail.
Thank You
import os, re
import email
import argparse
import olefile
def extractAttachment(msg, eml_files, output_path):
#print len(msg.get_payload())
#print msg.get_payload()
if len(msg.get_payload()) > 2:
if isinstance(msg.get_payload(), str):
try:
extractOLEFormat(eml_files, output_path)
except IOError:
#print 'Could not process %s. Try manual extraction.' % (eml_files)
#print '\tHeader of file: %s\n' % (msg.get_payload()[:8])
pass
elif isinstance(msg.get_payload(), list):
count = 0
while count < len(msg.get_payload()):
payload = msg.get_payload()[count]
#récupérer les pièces jointes
filename = payload.get_filename()
#os.rename(filename,'rrrrr'+filename)
#filename=os.path.join(str(filename), str(eml_files))
if filename is not None:
try:
magic = payload.get_payload(decode=True)[:4]
except TypeError:
magic = "None"
# Print the magic deader and the filename for reference.
printIT(eml_files, magic, filename)
# Write the payload out.
writeFile(filename, payload, output_path)
count += 1
elif len(msg.get_payload()) == 2:
payload = msg.get_payload()[1]
filename = payload.get_filename()
try:
magic = payload.get_payload(decode=True)[:4]
except TypeError:
magic = "None"
# Print the magic deader and the filename for reference.
printIT(eml_files, magic, filename)
# Write the payload out.
writeFile(filename, payload, output_path)
elif len(msg.get_payload()) == 1:
attachment = msg.get_payload()[0]
payload = attachment.get_payload()[1]
filename = attachment.get_payload()[1].get_filename()
try:
magic = payload.get_payload(decode=True)[:4]
except TypeError:
magic = "None"
# Print the magic deader and the filename for reference.
printIT(eml_files, magic, filename)
# Write the payload out.
writeFile(filename, payload, output_path)
#else:
# print 'Could not process %s\t%s' % (eml_files, len(msg.get_payload()))
def extractOLEFormat(eml_files, output_path):
data = '__substg1.0_37010102'
filename = olefile.OleFileIO(eml_files)
msg = olefile.OleFileIO(eml_files)
attachmentDirs = []
for directories in msg.listdir():
if directories[0].startswith('__attach') and directories[0] not in attachmentDirs:
attachmentDirs.append(directories[0])
for dir in attachmentDirs:
filename = [dir, data]
if isinstance(filename, list):
filenames = "/".join(filename)
filename = msg.openstream(dir + '/' + '__substg1.0_3707001F').read().replace('\000', '')
payload = msg.openstream(filenames).read()
magic = payload[:4]
# Print the magic deader and the filename for reference.
printIT(eml_files, magic, filename)
# Write the payload out.
writeOLE(filename, payload, output_path)
#filename = str(eml_files)+"--"+str(filename)
def printIT(eml_files, magic, filename):
filename = str(eml_files)+"--"+str(filename)
print ('Email Name: %s\n\tMagic: %s\n\tSaved File as: %s\n' % (eml_files, magic, filename))
def writeFile(filename, payload, output_path):
filename = str(eml_files)+"--"+str(filename)
try:
file_location = output_path + filename
open(os.path.join(file_location), 'wb').write(payload.get_payload(decode=True))
except (TypeError, IOError):
pass
def writeOLE(filename, payload, output_path):
open(os.path.join(output_path + filename), 'wb')
def main():
parser = argparse.ArgumentParser(description='Attempt to parse the attachment from EML messages.')
parser.add_argument('-p', '--path',default='C:\\Users\\hamd\\Desktop\\TEX\\emails' ,help='eml')#Path to EML files
parser.add_argument('-o', '--out', default='C:\\Users\\hamd\\Desktop\\TEX\\PJ\\eml_files\\',help='pj')#Path to write attachments to.
args = parser.parse_args()
if args.path:
input_path = args.path
else:
print ("You need to specify a path to your EML files.")
exit(0)
if args.out:
output_path = args.out
else:
print ("You need to specify a path to write your attachments to.")
exit(0)
for root, subdirs, files in os.walk(input_path):
for file_names in files:
eml_files = os.path.join(root, file_names)
msg = email.message_from_file(open(eml_files))
extractAttachment(msg, eml_files, output_path)
if __name__ == "__main__":
main()
I tried to write this as a comment but is was too long. I won't give a full blown solution, but I'll explain the idea.
A possible solution would be to create an hard link to the extracted attachment, giving to the hard link the same name of EML file. You can append an incremental suffix if you have more attachments in the same EML file:
whatever.eml (original email file)
whatever_001.attch (hard link to first extracted attachment)
whatever_002.attch (hard link to second extracted attachment)
...
This way:
you are free to move the extracted attachment anywhere else (but in the same disk, because hard links by definition work only on the same disk)
you can keep a copy of the attachment (the hard link) together with the EML file without consuming disk space
in case the extracted file is deleted you have a backup copy of the attachment (the hard links) without consuming disk space
In Python you can create an hard link simply with:
import os
os.link(existing_target_file, new_link_name)

Creating a function to ask user for a file

I'm trying to make function which asks the user for a filename. If the file is not found, it will keep asking. This what I have please help..
def return_text_file(infile):
while infile:
try:
file = open(infile)
except IOError:
print("Could not find the file specified")
infile = input ("Enter the file name")
return open_infile
file_input = input ("Enter the file name")
return_text_file(file_input)
You can create a function (e.g. ask_file_name below) to get a valid answer from the user. It will repeat constantly until an existing name is given.
import os
path_str = '/home/userblabla/ProjectBlabla/'
def ask_file_name():
files_detected = os.listdir(path_str)
while True:
print('\nFiles:')
for file in files_detected:
print(file)
file_name_given = input('\nFile name?')
if file_name_given not in files_detected:
print("Could not find the file specified")
else:
print('Thanks friend.')
return file_name_given
my_file_name = ask_file_name()
with open(my_file_name, 'r') as opened_file:
# Do stuff on opened_file
......
with open() automatically closes the file, and it might be better if you use it instead of open().

Resources