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?
#21
Quote: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.

I do not want to disturb you in a negative way. Perhaps someone else on this forum can provide me feedback on this thread?
Reply
#22
Quote:What does this part of the code below? Could you provide some explanation behind the lines of code as comments?

for example, filename = Path('/media/stubens/DataDrive-3XT/projs/T-Z/T/TryStuff/data/csv/IllinoisData.csv')
def read_csv_file(filename):

    parts = list(filename.parts)
    # parts = ['/', 'media', '/', 'stubens', '/', 'DataDrive-3XT','/', 'projs', '/', 'T-Z', '/', 'T', '/', 'TryStuff', '/', 'data', '/', 'csv', '/', 'IllinoisData.csv']

    parts[-1] = f"{filename.stem}Modified{filename.suffix}"
    # parts[-1] = 'IllinoisDataModified.csv'
    # parts = ['/', 'media', '/', 'stubens', '/', 'DataDrive-3XT','/', 'projs', '/', 'T-Z', '/', 'T', '/', 'TryStuff', '/', 'data', '/', 'csv', '/', 'IllinoisDataModified.csv']

    parts[0] = ''
    # removes '/' from index 0 because join will add it back again
    # parts = ['media', '/', 'stubens', '/', 'DataDrive-3XT','/', 'projs', '/', 'T-Z', '/', 'T', '/', 'TryStuff', '/', 'data', '/', 'csv', '/', 'IllinoisDataModified.csv']

    outfilename = Path(f"{'/'.join(parts)}")
    # join fileparts back together
    # outfilename = '/media/stubens/DataDrive-3XT/projs/T-Z/T/TryStuff/data/csv/IllinoisDataModified.csv'
 
    print(f"new output file name: {outfilename}")
    # will print
    # '/media/stubens/DataDrive-3XT/projs/T-Z/T/TryStuff/data/csv/IllinoisDataModified.csv'

    # open two files, filename as input (fp), outfilename as output (fout)
    with filename.open() as fp, outfilename.open('w') as fout:

        # set csv reader to flename (fp)
        crdr = csv.reader(fp, delimiter=',')

        # set csv writer to outfilename (fout), delimiter = ','
        cwrtr = csv.writer(fout, delimiter=',')

        # for each row in crdr (csv input)
        for row in crdr:

            # print the row
            print(row)

            # ...
            # Your code goes here
            # ...

            # write modified row
            cwrtr.writerow(row)
Python_User likes this post
Reply
#23
(Dec-07-2020, 10:17 PM)Larz60+ Wrote:
Quote:What does this part of the code below? Could you provide some explanation behind the lines of code as comments?

for example, filename = Path('/media/stubens/DataDrive-3XT/projs/T-Z/T/TryStuff/data/csv/IllinoisData.csv')
def read_csv_file(filename):

    parts = list(filename.parts)
    # parts = ['/', 'media', '/', 'stubens', '/', 'DataDrive-3XT','/', 'projs', '/', 'T-Z', '/', 'T', '/', 'TryStuff', '/', 'data', '/', 'csv', '/', 'IllinoisData.csv']

    parts[-1] = f"{filename.stem}Modified{filename.suffix}"
    # parts[-1] = 'IllinoisDataModified.csv'
    # parts = ['/', 'media', '/', 'stubens', '/', 'DataDrive-3XT','/', 'projs', '/', 'T-Z', '/', 'T', '/', 'TryStuff', '/', 'data', '/', 'csv', '/', 'IllinoisDataModified.csv']

    parts[0] = ''
    # removes '/' from index 0 because join will add it back again
    # parts = ['media', '/', 'stubens', '/', 'DataDrive-3XT','/', 'projs', '/', 'T-Z', '/', 'T', '/', 'TryStuff', '/', 'data', '/', 'csv', '/', 'IllinoisDataModified.csv']

    outfilename = Path(f"{'/'.join(parts)}")
    # join fileparts back together
    # outfilename = '/media/stubens/DataDrive-3XT/projs/T-Z/T/TryStuff/data/csv/IllinoisDataModified.csv'
 
    print(f"new output file name: {outfilename}")
    # will print
    # '/media/stubens/DataDrive-3XT/projs/T-Z/T/TryStuff/data/csv/IllinoisDataModified.csv'

    # open two files, filename as input (fp), outfilename as output (fout)
    with filename.open() as fp, outfilename.open('w') as fout:

        # set csv reader to flename (fp)
        crdr = csv.reader(fp, delimiter=',')

        # set csv writer to outfilename (fout), delimiter = ','
        cwrtr = csv.writer(fout, delimiter=',')

        # for each row in crdr (csv input)
        for row in crdr:

            # print the row
            print(row)

            # ...
            # Your code goes here
            # ...

            # write modified row
            cwrtr.writerow(row)

Thanks!!
Reply
#24
from tkinter.filedialog import askopenfilename
from pathlib import Path
import sys
import csv

def get_filename():
    filename = Path(askopenfilename(filetypes=[("CSV files","*.csv")]))

    return filename


def read_csv_file(filename):
    parts = list(filename.parts)


if __name__ == '__main__':              #This executes the code!
    read_csv_file(get_filename())
If I run the above code, I have the Unused variable 'parts'pylint(unused-variable) message. I do understand the parts variable is not defined, but how can it run anyway in the code Larz60 provided me? I can't find the variable parts defined in the code anyway...
Reply
#25
Python_User Wrote:I can't find the variable parts defined in the code anyway...
parts is an attribute pathlib that Larz60+ use here.
That Pylint complain about can you just ignore,as it's not error just that Pylint struggle whit pathlib.

Also is not necessary to split it up parts as done here,can just read filename
from tkinter.filedialog import askopenfilename
from pathlib import Path
import csv
 
def get_filename():
    filename = Path(askopenfilename(filetypes=[("CSV files", "*.csv")])) 
    return filename
 
def read_csv_file(filename):
    # parts = list(filename.parts)
    with open(filename) as fp:    
        crdr = csv.reader(fp, delimiter=',') 
        for row in crdr:
            print(row)    

if __name__ == '__main__':          
   read_csv_file(get_filename())
Output:
['name', 'origin', 'dest'] ['xxx', 'uk', 'france'] ['yyyy', 'norway', 'finland'] ['zzzz', 'denmark', 'canada']
Reply
#26
Just to clarify:

In the original code (posted below again), parts was used to create the output file name, and had nothing to do with input file name (as requested by member). There are several ways to do this, I chose splitting into parts, adding in 'Modified' to end of filename, and joining back together.

Original code:
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())
Please note f-strings are not being properly displayed. items within brackets should be highlighted as they are placeholders for the variable they contain.
Reply


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