Python Forum
Closing Files - CSV Reader/Writer
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Closing Files - CSV Reader/Writer
#1
Hello,

I am trying to write a script which will:
1. Download all the emails in a specific Outlook folder to a directory on my machine (.msg format)
2. Loop through each .msg file and create a .csv

The contents of the email is a tab-delimited table. So, I am basically saving the email message which contains the table and trying to convert it into a CSV file.

What I have works but I want to improve. Specifically: do I need to create a text file for this? It's a file I don't require and am deleting manually. If I don't need it, how can I adjust my script?

Also, and probably relatedly, what is the best approach to closing the file? Running the script seems to leave the file still open and need to restart my kernel (using Jupyter) before I can work with the files. I have tried adjust the following line to have it in a with block but getting stuck on how to adjust it to also use the delimiter (getting type errors).

    in_txt = csv.reader(open(text_file_string, "r"), delimiter = '\t')
Thanks for any help!
lummers

import extract_msg
import csv
import os
import pathlib
import glob
import pathlib
from win32com.client import Dispatch

# This block will find all the messages in a specifc Outlook folder and save them to specific directory on desktop

outlook = Dispatch("Outlook.Application").GetNamespace("MAPI") 
inbox = outlook.GetDefaultFolder(6).Folders.Item("Container Data")

messages = inbox.items

savepath = r'C:\Users\lummers\Downloads\2020-05-24 shadow results\location' 

for msg in messages:
    name = str(msg.subject)
    name = name + '.msg'
    name = name.replace(":","--")
    finalsavepath = os.path.join(savepath, name)
    # print(finalsavepath)
    msg.saveas(finalsavepath) 



path = r'C:\Users\lummers\Downloads\2020-05-24 shadow results\location' 
files = os.listdir(path)

#Creates a list for every .msg file in the path
msg_files = [i for i in files if i.endswith('.msg')]

#Esablish new list called pathfiles
#Loops through the msg_files list and appends the filepath of .msg file to the new list

pathfiles = []

for i in msg_files: 
    createpath = os.path.join(path, i)
    pathfiles.append(createpath)


for i in pathfiles:
    msg = extract_msg.Message(i)
    email_body = msg.body
    
    email_body_output = email_body.replace("\t \r\n", "\t \r")
    
    text_file_string = i + str(".txt")
    csv_file_string = i + str(".csv")
    
    text_file = open(text_file_string, "w")
    n = text_file.write(email_body_output)
    text_file.close()

    in_txt = csv.reader(open(text_file_string, "r"), delimiter = '\t')

    with (open(csv_file_string, 'w', newline='')) as f:
        writer = csv.writer(f)
        writer.writerows(in_txt)
Reply
#2
You can use something like os.remove("file_name.csv") to remove unwanted files.
Reply
#3
You want to close the file? Isn't that why use the with statement, so don't we don't have to close it? That's what i heard.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Csv writer meaning of quoting mg24 2 1,134 Oct-01-2022, 02:16 PM
Last Post: Gribouillis
  [split] NameError: name 'csvwriter' is not defined. Did you mean: 'writer'? cathy12 4 3,301 Sep-01-2022, 07:41 PM
Last Post: deanhystad
  xml simple reader kucingkembar 2 1,051 Aug-19-2022, 08:51 PM
Last Post: kucingkembar
Sad pandas writer create "corrupted" file freko75 1 2,805 Jun-14-2022, 09:57 PM
Last Post: snippsat
  CSV writer - no output?? Clives 6 2,533 Mar-30-2022, 04:09 PM
Last Post: Clives
  Having strange results from an RFID HID card reader - I'm stuck orbisnz 1 1,477 Mar-28-2022, 08:20 AM
Last Post: Larz60+
  Thoughts on interfacing with a QR code reader that outputs keystrokes? wrybread 1 1,467 Oct-08-2021, 03:44 PM
Last Post: bowlofred
  NFC reader code help johnroberts2k 1 2,566 Jul-02-2021, 08:43 PM
Last Post: deanhystad
  csv.reader(): Limit the number of columns read in Windows Pedroski55 9 5,186 Jan-23-2021, 01:03 AM
Last Post: pjfarley3
  Opening and closing Mac applications and files Nickd12 5 5,682 Sep-05-2020, 04:39 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020