Python Forum
Problem with reading and writing to file.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with reading and writing to file.
#1
Hi
I got a code for a csv database where i can write a bit of data and it saves it to a csv file very simple.
My problem is that every time i start the code it overwrite the old csv file and i start up with an empty file. I have no ide what to do. Could any one help me out?


#imports
import csv

#Variables
current_ID = 1

new_additions = []

filename = "library.csv"

fields = ['ID', 'Title', 'Author', 'Genre', 'Year', 'Location']

data = []

#Code
with open(filename, 'w+') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        data.append(dict(row))
if len(data) > 0:
    current_ID = data[:-1].get("ID")
    current_ID = int(current_ID) + 1

print("------Welcome to the Python Library organiser------")

choice = ""

while choice.lower() != "x":
    print("""What would you like to do?
    1 - Add a book
    2 - Display your Books
    3 - Search for a Book""")

    choice = input(">")

    if choice == "1":
        #Code to add a record
        new_record = {
            "ID": current_ID,
            "Title": input("What is the title of the book? >"),
            "Author": input("What is the author's first name?  >"),
            "Genre": input("What genre is the book?  >"),
            "Year": input("What year was the book released?  >"),
            "Location": input("Where is the book? > ")
        }
        new_additions.append(new_record)
        current_ID = current_ID + 1
        print("-"*15)
        print("New Record added successfully!")
    elif choice == "2":
        #Display the data
        for item in fields:
            print("%-25s"%item, end='')
        print("\n")
        for row in data:
            for key, val in row.items():
                print("%-25s"%val, end='')
            print("\n")
        for row in new_additions:
            for key, val in row.items():
                print("%-25s"%val, end='')
            print("\n")
    elif choice == "3":
        #Search the data
        search_term = input("What would you like to search for?").lower()
        results = []
        for row in data:
            for key, val in row.items():
                if search_term in val.lower():
                    results.append(row)
        for item in new_additions:
            for key, val in item.items():
                if search_term in val.lower():
                    results.append(item)
        #Display the results
        if len(results) > 0:
            for item in fields:
                print("%-25s"%item, end='')
            print("\n")
            for item in results:
                for key, val in item.items():
                    print("%-25s"%val, end='')
                print("\n")
        else:
            print("Sorry no records found")
    elif choice.lower() == "x":
        print("Thank you! Shutting down.")
    else:
        print("Sorry, I didnt recognise that option")
        
if len(new_additions) > 0:
    with open(filename, 'a') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fields)
        writer.writeheader()
        for item in new_additions:
            writer.writerow(item)
Reply
#2
Opening it in write mode (line 16) is erasing the file. Open it in read mode ('r'). Note that line 21 also has an error. data[:-1] is a slice because of the colon, so it's a list, which has not get method. Change that to data[-1], which will just return the last line read.

Why only the first name of the author?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Jul-20-2019, 05:54 PM)ichabod801 Wrote: Opening it in write mode (line 16) is erasing the file. Open it in read mode ('r'). Note that line 21 also has an error. data[:-1] is a slice because of the colon, so it's a list, which has not get method. Change that to data[-1], which will just return the last line read.

Why only the first name of the author?

Thank you. Honesly i dont know why its only the first name. Its not my code i found it on a blog from the raspberry pi home page i tought i could do something else with it.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Sad problems with reading csv file. MassiJames 3 559 Nov-16-2023, 03:41 PM
Last Post: snippsat
  Reading a file name fron a folder on my desktop Fiona 4 851 Aug-23-2023, 11:11 AM
Last Post: Axel_Erfurt
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,046 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Reading a file JonWayn 3 1,057 Dec-30-2022, 10:18 AM
Last Post: ibreeden
  Reading Specific Rows In a CSV File finndude 3 940 Dec-13-2022, 03:19 PM
Last Post: finndude
  Excel file reading problem max70990 1 865 Dec-11-2022, 07:00 PM
Last Post: deanhystad
  Replace columns indexes reading a XSLX file Larry1888 2 951 Nov-18-2022, 10:16 PM
Last Post: Pedroski55
Bug Writing in a document problem IOHANNES 4 1,017 Oct-26-2022, 08:58 PM
Last Post: IOHANNES
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,305 Sep-27-2022, 01:38 PM
Last Post: buran
  Failing reading a file and cannot exit it... tester_V 8 1,753 Aug-19-2022, 10:27 PM
Last Post: tester_V

Forum Jump:

User Panel Messages

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