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
  Wish to write a code for an electronic load and a power supply for measuring Eff Hasan2025 4 1,899 Jun-18-2025, 06:40 AM
Last Post: Hasan2025
  needing some help to write some code for a game calculator rymdaksel 2 2,364 Mar-08-2025, 03:02 AM
Last Post: bevisandrew
  Delete file with read-only permission, but write permission to parent folder cubei 6 28,782 Jun-01-2024, 07:22 AM
Last Post: Eleanorreo
  UART write binary code trix 3 2,424 Apr-28-2024, 04:57 PM
Last Post: deanhystad
  No Module found in other directory than source code [SOLVED] AlphaInc 1 4,059 Nov-10-2021, 04:34 PM
Last Post: AlphaInc
  How to write a code with İF function? Aycaaxx 1 3,069 Nov-03-2020, 05:46 AM
Last Post: deanhystad
  Getter/Setter : get parent attribute, but no Getter/Setter in parent nboweb 2 5,297 May-11-2020, 07:22 PM
Last Post: nboweb
  Running tests in a sibling directory to code sodhiar 1 5,002 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 3,952 Sep-23-2019, 11:01 AM
Last Post: Larz60+
  How do i write tests for this code? hshivaraj 0 2,923 Apr-27-2019, 05:28 PM
Last Post: hshivaraj

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.