Python Forum

Full Version: io.UnsupportedOperation: not readable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I've already imported csv, so I don't understand why it's complaining about line 20 in the following code:

#!/usr/bin/env python3
#MovieListCSV.py
#This program does pretty much the same thing as MovieList2D.py. The only
#difference about this program is that it calls the writeMovies function
#whenever the user updates the list, so that the data is still saved if this
#program crashes.
import csv

FILENAME = "movies.csv"

def writeMovies(movies):
    with open(FILENAME, "w", newline="") as file:
        writer = csv.writer(file)
        writer.writerows(movies)

def readMovies():
    movies = []
    with open(FILENAME, "w", newline="") as file:
        reader = csv.reader(file)
        for row in reader:
            movies.append(row)
        return movies

def listMovies(movies):
    for i in range(len(movies)):
        movie = movies[i]
        print(str(i+1) + ". " + movie[0] + " (" + movie[1] + ")")
    print()

def addMovie(movies):
    name = input("Name: ")
    year = input("Year: ")
    movie = []
    movie.append(name)
    movie.append(year)
    movies.append(movie)
    writeMovies(movies)
    print(name + " was added.\n")

def deleteMovie(movies):
    index = int(input("Movie Number: "))
    movie = movies.pop(index - 1)
    writeMovies(movies)
    print(movie[0] + " was deleted.\n")

def displayMenu():
    print("COMMAND MENU")
    print("list - List all movies")
    print("add  - Add a movie")
    print("del  - Delete a movie")
    print("exit - Exit the program")
    print()

def main():
    displayMenu()
    movies = readMovies()
    while True:
        command = input("Enter Command: ")
        if command.lower() == "list":
            listMovies(movies)
        elif command.lower() == "add":
            addMovie(movies)
        elif command.lower() == "del":
            deleteMovie(movies)
        elif command.lower() == "exit":
            break
        else:
            print("Invalid command. Please try again.")
    print("Bye!")

if __name__ == "__main__":
    main()
Error:
Traceback (most recent call last): File "I:\Python\Python36-32\SamsPrograms\MovieListCSV.py", line 72, in <module> main() File "I:\Python\Python36-32\SamsPrograms\MovieListCSV.py", line 56, in main movies = readMovies() File "I:\Python\Python36-32\SamsPrograms\MovieListCSV.py", line 20, in readMovies for row in reader: io.UnsupportedOperation: not readable >>>
The opened file is in write mode not 'r' for reading.
The error "line 20" is likely referring to the line where the code is attempting to open the CSV file for writing. The specific error message would be more helpful in identifying the exact issue.

One possible cause of the error is that the file "movies.csv" may not exist. If the file doesn't exist, you'll need to create it before attempting to open it for writing.