Python Forum
How to rename a CSV file by adding MODIFIED in the filename?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to rename a CSV file by adding MODIFIED in the filename?
#11
Here's some code that will open a csv file, modify the filename and write back to new file name that is the same as the input, and in the same directory, byt with 'Modified' added to filename.
there is a comment where you can insert code to modify the input record before writing back out.

Try it out:
import csv
from pathlib import Path
from tkinter.filedialog import askopenfilename
import sys


def read_csv_file(filename):
    parts = list(filename.parts)
    parts[-1] = f"{filename.stem}Modified{filename.suffix}"
    parts[0] = ''
    outfilename = Path(f"{'/'.join(parts)}")

    print(f"new output file name: {outfilename}")

    with filename.open() as fp, outfilename.open('w') as fout:
        crdr = csv.reader(fp, delimiter=',')
        cwrtr = csv.writer(fout, delimiter=',')
        for row in crdr:
            print(row)
            # Modify row as desired here
            cwrtr.writerow(row)

def get_filename():
    badcount = 0

    while(True):
        try:
            if badcount > 2:
                print("Three strikes and your out!")
                sys.exit(-1)
            filename = Path(askopenfilename(filetypes=[("CSV files","*.csv")]))
            break
        except TypeError:
            badcount += 1
            print(f"bad filename, try again")
        
    return filename


if __name__ == '__main__':
    read_csv_file(get_filename())
Reply


Messages In This Thread
RE: How to rename a CSV file by adding MODIFIED in the filename? - by Larz60+ - Dec-01-2020, 02:08 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Rename first row in a CSV file James_S 3 693 Dec-17-2023, 05:20 AM
Last Post: James_S
  PDF properties doesn't show created or modified date Pedroski55 4 1,230 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  rename file RolanRoll 0 580 May-18-2023, 02:17 PM
Last Post: RolanRoll
  File path by adding various variables Mishal0488 2 1,181 Apr-28-2023, 07:17 PM
Last Post: deanhystad
  '' FTP '' File upload with a specified string and rename midomarc 1 1,273 Apr-17-2023, 03:04 AM
Last Post: bowlofred
  output provide the filename along with the input file processed. arjunaram 1 1,001 Apr-13-2023, 08:15 PM
Last Post: menator01
  rename same file names in different directories elnk 0 773 Nov-04-2022, 05:23 PM
Last Post: elnk
  rename and add desire "_date" to end of file name before extention RolanRoll 1 1,311 Jun-13-2022, 11:16 AM
Last Post: gruntfutuk
  Rename part of filename in multiple files atomxkai 7 7,605 Feb-18-2022, 10:03 PM
Last Post: atomxkai
  Adding to an XML file TeXaSpEtE83 0 1,314 Dec-22-2021, 08:28 AM
Last Post: TeXaSpEtE83

Forum Jump:

User Panel Messages

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