Python Forum
Deleting a line in a csv file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Deleting a line in a csv file
#1
I just can't figure out how to do this :(

I've got a csv file with this content:
Main,Daan,Daanssen,[email protected],Tennon straat,39,4124KE,Buren,0634582938
Second,Jens,Daanssen,[email protected],Tennon straat,30,4124KE,Endracht,0634582938
Third,harry,Daanssen,[email protected],Tennon straat,30,4124KE,Endoort,0634582938

I want to create a piece of code, that is able to delete a whole line by choice.
The user gives the first word of the line (for example: Main), and the code should delete the line that starts with the word Main.

Does someone know how to do this? Thanks in advance!
Reply
#2
I would loop through the contents of the file and write each one to a new file, unless it qualifies for skipping. It should be pretty straightforward, if you give it a try we'd be happy to help with any details that you have trouble with. (Note, you can't modify files in-place in this way, though you can create the illusion of doing so by renaming the new file to the old file's name.)
Reply
#3
import pandas as pd

file = pd.read_csv('Profiles.txt', delimiter=',')
counter = 0
while True:
    try:
        profile = file.iloc[counter, 0]
    except Exception:
        print('%s ERROR: No profiles loaded%s' % (fg(196), attr(0)))
        time.sleep(2)
        clear()
        profiles()
    else:
        if profile == want_delete:
            line_delete = teller + 1
            break
        else:
            counter += 1

# HERE SHOULD COME THE CODE THAT DELETES THE LINE: line_delete. 
Have you got advice on how to do this?

(Feb-24-2020, 11:12 PM)julio2000 Wrote:
import pandas as pd

# THE OTHER PART OF THE CODE IS NOT IMPORTANT

file = pd.read_csv('Profiles.txt', delimiter=',')
counter = 0
while True:
    try:
        profile = file.iloc[counter, 0]
    except Exception:
        print('%s ERROR: No profiles loaded%s' % (fg(196), attr(0)))
        time.sleep(2)
        clear()
        profiles()
    else:
        if profile == want_delete:
            line_delete = teller + 1
            break
        else:
            counter += 1

# HERE SHOULD COME THE CODE THAT DELETES THE LINE: line_delete. 
Have you got advice on how to do this?

(Feb-24-2020, 11:12 PM)julio2000 Wrote:
import pandas as pd

# THE OTHER PART OF THE CODE IS NOT IMPORTANT

file = pd.read_csv('Profiles.txt', delimiter=',')
counter = 0
while True:
    try:
        profile = file.iloc[counter, 0]
    except Exception:
        print('%s ERROR: No profiles loaded%s' % (fg(196), attr(0)))
        time.sleep(2)
        clear()
        profiles()
    else:
        if profile == want_delete:
            line_delete = teller + 1
            break
        else:
            counter += 1

# HERE SHOULD COME THE CODE THAT DELETES THE LINE: line_delete. 
Have you got advice on how to do this?
Reply
#4
You most tell in your post @julio2000 that you are gone use Pandas.
Then the answer bye micseydel will not be the way as Pandas has it own ways of doing most stuff,
as example not looping trough file as would in do regular Python code.
>>> import pandas as pd

>>> file = pd.read_csv('csv_f.csv', delimiter=',', header=None)
>>> file
        0      1         2             3              4   5       6         7          8
0    Main   Daan  Daanssen  [email protected]  Tennon straat  39  4124KE     Buren  634582938
1  Second   Jens  Daanssen  [email protected]  Tennon straat  30  4124KE  Endracht  634582938
2   Third  harry  Daanssen  [email protected]  Tennon straat  30  4124KE   Endoort  634582938

>>> del_row_with = 'Main'
>>> df = file[~file[0].str.startswith(del_row_with)]
>>> df
        0      1         2             3              4   5       6         7          8
1  Second   Jens  Daanssen  [email protected]  Tennon straat  30  4124KE  Endracht  634582938
2   Third  harry  Daanssen  [email protected]  Tennon straat  30  4124KE   Endoort  634582938
Reply
#5
Well i would prefer to not use pandas, cause with pandas you'll need to use row titles and stuff. But panda seemed the best option to do this I believe.

Btw thanks! It does work in the python console, but i don't see any changes in the csv file, wich i do want to happen. do you know why de csv file doesn't change?
Reply
#6
(Feb-25-2020, 11:24 AM)julio2000 Wrote: but i don't see any changes in the csv file, wich i do want to happen. do you know why de csv file doesn't change?
Have to save the DataFrame,take away index and header then get a clean .csv if that's what you want.
import pandas as pd

file = pd.read_csv('csv_f.csv', delimiter=',', header=None)
del_row_with = 'Main'
df = file[~file[0].str.startswith(del_row_with)]
print(df)
df.to_csv(r'out.csv', index=False, header=False)
Output:
Second,Jens,Daanssen,[email protected],Tennon straat,30,4124KE,Endracht,634582938 Third,harry,Daanssen,[email protected],Tennon straat,30,4124KE,Endoort,634582938
Reply
#7
yess perfect! It works! thanks a lot!!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  File "<string>", line 19, in <module> error is related to what? Frankduc 9 12,508 Mar-09-2023, 07:22 AM
Last Post: LocklearSusan
  Getting last line of each line occurrence in a file tester_V 1 856 Jan-31-2023, 09:29 PM
Last Post: deanhystad
  deleting columns in CSV file astral_travel 8 2,306 Nov-26-2022, 09:36 PM
Last Post: astral_travel
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,356 Sep-27-2022, 01:38 PM
Last Post: buran
  Print to a New Line when Appending File DaveG 0 1,214 Mar-30-2022, 04:14 AM
Last Post: DaveG
  Find and delete above a certain line in text file cubangt 12 3,440 Mar-18-2022, 07:49 PM
Last Post: snippsat
  CSV to Text File and write a line in newline atomxkai 4 2,669 Feb-15-2022, 08:06 PM
Last Post: atomxkai
  writelines only writes one line to file gr3yali3n 2 2,360 Dec-05-2021, 10:02 PM
Last Post: gr3yali3n
  [Solved] Reading every nth line into a column from txt file Laplace12 7 5,208 Jun-29-2021, 09:17 AM
Last Post: Laplace12
Exclamation Why there's a 'blank line' on CSV file? brunolelli 4 3,049 Mar-25-2021, 03:43 AM
Last Post: buran

Forum Jump:

User Panel Messages

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