Python Forum
write code that resides in parent directory
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
write code that resides in parent directory
#1
New to Python and have a question on usage. I am using Linux. I have a Python 3.11 program that reads, parses, and writes an ics file that works if it is in the same directory as the files. I would like to have it not have to be in the same directory but in the parent directory. Any insights are welcome.

from pathlib import Path
ROOT_DIR = Path(__file__).parent
ics_file = input('\n ics file name?')
if('.ics'not in ics_file):
        ics_file = ics_file + ".ics"
output_file = input('\n csv file name?')
if('.csv'not in output_file):
        output_file = output_file + ".csv"
date_range = input('\n date range (YYYYMM)')
INPUT_FILE = ROOT_DIR / ics_file
OUTPUT_FILE = ROOT_DIR / output_file
print(ROOT_DIR)
print(INPUT_FILE)
print(OUTPUT_FILE)
print(ROOT_DIR.parent)
if not INPUT_FILE.exists():
        print("ICS file not found")

TARGET_LINE = 'SUMMARY:'
DATE_LINE = 'DTSTART;VALUE=DATE:'

fp = open(OUTPUT_FILE,"w")
output_lines = []    
contents = INPUT_FILE.read_text().strip().splitlines()

for line_num, line in enumerate(contents, 1):
    if line.startswith(DATE_LINE):
        y = line.strip(DATE_LINE)
       
    elif line.startswith(TARGET_LINE):
        x = line.strip(TARGET_LINE)
        if(date_range in y):
            fp.write(str(y)+", ")
            fp.write(x)
            fp.write("\n")   
       
print('DONE') 
Reply
#2
The following will get the absolute paths.
Note that root_dir will get path to the file, including the python file name.
If you just wanted the current path, use root_dir = Path('.')
You would also have to assure that the current path is the the same as __file__ path.
You can still use __file__. but to get previous directory,would need parent_dir = root_dir.parent.parent.absolute()
root_dir = Path(__file__).absolute()
print(root_dir)
parent_dir = root_dir.parent.absolute()
print(parent_dir)
Reply
#3
(Mar-29-2024, 12:03 AM)franklin97355 Wrote: Any insights are welcome.
I would rather use the builtin argparse module to handle the arguments instead of having user interaction. For example you could invoke
Output:
python franklin.py -m 202403 -o ../foo/ham.csv spam.ics
Among other benefits, this allows you to invoke the program in a makefile for example. Here is a possible version
from argparse import ArgumentParser
from pathlib import Path
import sys

TARGET_LINE = "SUMMARY:"
DATE_LINE = "DTSTART;VALUE=DATE:"

parser = ArgumentParser(description='Convert .ics file into .csv')
parser.add_argument(
    "-o",
    "--outfile",
    dest="outfile",
    default="",
    action="store",
    required=False,
    help="Destination CSV file, defaults to stdout",
    metavar="OUTFILE",
)
parser.add_argument(
    "-m",
    "--month",
    dest="month",
    action="store",
    required=True,
    help="Month in format YYYYMM",
    metavar="YYYYMM",
)
parser.add_argument(dest="infile", help="Source ICS file", metavar="INFILE")


def process_lines(lines, date_range, fp):
    for line_num, line in enumerate(lines, 1):
        if line.startswith(DATE_LINE):
            y = line.strip(DATE_LINE)

        elif line.startswith(TARGET_LINE):
            x = line.strip(TARGET_LINE)
            if date_range in y:
                fp.write(str(y) + ", ")
                fp.write(x)
                fp.write("\n")


def main():
    args = parser.parse_args()
    print(args)
    if not args.infile.endswith(".ics"):
        args.infile = args.infile + ".ics"
    infile = Path(args.infile)
    if not infile.is_file():
        print(f"Error: ICS file not found: {args.infile}", file=sys.stderr)
        return 1
    lines = infile.read_text().strip().splitlines()
    if args.outfile:
        if not args.outfile.endswith(".csv"):
            args.outfile = args.outfile + ".csv"
        with open(args.outfile, "w") as ofp:
            process_lines(lines, args.month, ofp)
        print(f"Output written to: {args.outfile}")
    else:
        process_lines(lines, args.month, sys.stdout)
    return 0


if __name__ == "__main__":
    sys.exit(main())
Here is the help automatically generated by this program
Output:
λ python paillasse/pf/franklin97355.py -h usage: franklin97355.py [-h] [-o OUTFILE] -m YYYYMM INFILE Convert .ics file into .csv positional arguments: INFILE Source ICS file options: -h, --help show this help message and exit -o OUTFILE, --outfile OUTFILE Destination CSV file, defaults to stdout -m YYYYMM, --month YYYYMM Month in format YYYYMM
« We can solve any problem by introducing an extra level of indirection »
Reply
#4
Thank you, I was remiss in not checking my forum posts. Now I will check your suggestions and see if I can make heads or tails out of that. Again thanks to you two.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  UART write binary code trix 3 310 Apr-28-2024, 04:57 PM
Last Post: deanhystad
  needing some help to write some code for a game calculator rymdaksel 1 468 Jan-02-2024, 09:56 AM
Last Post: deanhystad
  No Module found in other directory than source code [SOLVED] AlphaInc 1 2,105 Nov-10-2021, 04:34 PM
Last Post: AlphaInc
  How to write a code with İF function? Aycaaxx 1 1,869 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  Hi Guys, please help me to write SAS macro parameter equivalent code in Python Manohar9589 2 2,639 Jun-14-2020, 05:07 PM
Last Post: Larz60+
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 3,027 May-11-2020, 07:22 PM
Last Post: nboweb
  Running tests in a sibling directory to code sodhiar 1 2,742 Nov-07-2019, 11:28 PM
Last Post: MckJohan
  How do I read the HTML files in a directory and write the content into a CSV file? glittergirl 1 2,619 Sep-23-2019, 11:01 AM
Last Post: Larz60+
  How do i write tests for this code? hshivaraj 0 2,045 Apr-27-2019, 05:28 PM
Last Post: hshivaraj
  How to fix error code 2 in python, “directory not found”? dav3javu 1 7,085 Apr-03-2019, 04:55 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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