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
#12
Whoo, this is some heavy code for me Big Grin . To be honest, I am already lost after the first 11 lines of code. What should you advise studying code like this? I tried learning the book "Automate the boring Stuff with Python", but every time I getting the feeling coding just isn't something for me...
Reply
#13
Try running it. If you like it, I can go into some detail.
Have to eat my supper now, but will be back on this evening.
Reply
#14
Thank you Larz60, I am going to study the code supported with the python books I have this weekend, I am quite busy with work at the moment. I will let you know if problems occurs. Thanks for offering your help in this :).
Reply
#15
Hey Larz60,

What is the function of path in filename = Path(askopenfilename(filetypes=[("CSV files","*.csv")]))?

And where does the askopenfilename function refers to? Because when I run the code, it always opens the same folder on my local disc(:C).

from pathlib import Path
from tkinter.filedialog import askopenfilename

#Test 01 ---------------------------------------
#filename = Path(askopenfilename(filetypes=[("CSV files","*.csv")]))

#Test 02 ---------------------------------------
filename = askopenfilename(filetypes=[("CSV Files", "*.csv")])
print (filename)
Reply
#16
Quote:What is the function of path in filename = Path(askopenfilename(filetypes=[("CSV files","*.csv")]))?
opens a filedialog, and returns path and name of selected file

Quote:And where does the askopenfilename function refers to?
it is a navigable window, select the directory you want, then double click on the file you want to open.
Reply
#17
What does this part of the code below? Could you provide some explanation behind the lines of code as comments?

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)
Reply
#18
As addition, why isn't root = Tk() used in this code?

In the video below at 03:45 the guy says this should be used always in Tkinter...?
Tkinter root
Reply
#19
The delimiter isn't working in this code? When I change it to ':' I still see the comma's as delimiters...

        crdr = csv.reader(fp, delimiter=':')
        cwrtr = csv.writer(fout, delimiter=':')
Reply
#20
Quote:Python_user writes:
As addition, why isn't root = Tk() used in this code?
In the video below at 03:45 the guy says this should be used always in Tkinter...?
The 'guy' is only partially correct, There are some tkinter modules that can be run as stand alone.
The filedialog and messagebox are examples of this.
Technically, perhaps a root window should be created, but these classes function without.
Don't forget, tkinter is just a wrapper around tcl/tk.

Quote:Could you provide some explanation behind the lines of code as comments?
perhaps I can get to documenting the entire code.
I wrote it in 10 minutes, and haden't planned on documenting, I have my regular work to do, as well as answering so many questions (as a volunteer) on the forum.
Always glad to answer specific questions.
Reply


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