Saving a Python list to a CSV file will empty the list

I'm currently experimenting with lists, the enumerate() method, and CSV files.

In my process, I am using the writerows() method to store an enumerate object in a .csv file. However, once the writing is complete, the list/enumerate object ends up empty.

Why does this occur? Is there a way to retain the values in my list (perhaps by saving them in another variable)?

My setup involves Windows 10 and Python 3.6.4.

Below you will find the code snippet:

import csv

b = [1,2,3,4,5,6,7,8,9,10,11,"lol","hello"]
c = enumerate(b)

with open("output.csv", "w", newline='') as myFile:
    print("Writing CSV")
    writer = csv.writer(myFile)
    writer.writerows(c)

print(list(c))

Output:

>> Writing CSV
>> []
>> [Finished in 0.1s]

If I execute: print(list(c)) before the writing operation, c also becomes empty.

Thank you!

Answer №1

my_variable = enumerate(some_list)

In this case, my_variable is not a list but a generator. Generators are consumed when iterated over.

You will need to create a new generator each time you want to use it.

If you need a permanent reference to the fully exhausted content of the generator, you must convert it into a list.

my_variable = list(enumerate(some_list))

Answer №2

It is completely normal. The variable c functions as a generator that goes through all the elements in b, running through it just once. This occurs when you execute writer.writerows(c).

Once this process is complete, the generator becomes empty, resulting in an empty list if you try to convert it into a list.

Answer №3

[Python]: enumerate(iterable, start=0) is known for returning a generator.

According to [Python]: Generators:

The main advantage of generators lies in their lazy (on-demand) generation of values, leading to lower memory usage. Unlike traditional methods, we do not have to generate all elements at once before using them. This efficiency is similar to iterators, but generators simplify the process of creating iterators.
...
Note: Generators are only advantageous if the generated values are used just once.

Once you iterate through a generator, its values are consumed and cannot be reused. Saving the values can be done by converting the generator into a list, which also consumes it as it iterates over the values.

Further insights can be found in [SO]: How do I list all files of a directory? (@CristiFati's answer - Part One) (Preliminary notes section - where the behavior of [Python]: map(function, iterable, ...) is illustrated).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Insider's guide to showcasing code in vibrant colors using Python Django

Context: I am currently working on a Python Django web application and need to showcase code snippets in the browser with syntax highlighting. An example of the code snippet I want to display would be: if True: print("Hello World") I am look ...

An issue with Selenium web scraping arises: WebDriverException occurs after the initial iteration of the loop

Currently, I am executing a Selenium web-scraping loop on Chrome using MacOS arm64. The goal is to iterate through a list of keywords as inputs in an input box, search for each one, and retrieve the text of an attribute from the output. A few months ago, I ...

What is the process for providing arguments to a class at the time of object instantiation?

I am in the process of developing a graphical user interface that features two buttons, "Choose Input File" and "Execute". Upon clicking on "Open Input File", users have the ability to select a file from their computer containing URLs in a single column. S ...

Exploring the world of Python mix-ins through the main typing class

I have a group of mixins within my class: class MyObject(MyObjectFilesMixin, MyObjectProcessingMixin, ...): def __init__(self, value): self.value = self.preprocess(value) One of the mixins is structured like this: class MyObjectFilesMixin: ...

I am looking to convert a list of dictionaries into a list of lists using Python

I am attempting to convert a list of dictionaries into a list of lists in Python. Here is an example of the data: before_data = [ { "itemid": "23743", "lastclock": "1574390042", "lastvalue": "2798", "name": "cl Loaded ...

Choosing which columns to copy from a Pandas DataFrame

I want to duplicate my current df to another pandas dataframe. If I specify columns to copy, I can do so like this: df_copy = df[['col_A', 'col_B', 'col_C']].copy() Is there a way to copy all columns except for the ones spec ...

Fix the exit button functionality in my game featuring turtles

Can someone help me create an exit button within my code? I tried using exit() but encountered issues. If utilizing exit() is not feasible, alternative approaches are also welcome. Kindly provide a detailed explanation of the solution -- thank you in adv ...

Once more: "The JSON object should be a string, bytes, or bytearray, not a list" encountered in the requests library

I'm struggling with a simple request and can't figure out what's wrong data1 = df.loc[N, 'online_raw_json'] print(type(data1)) print(data1) data1 = json.dumps(data1) print(type(data1)) print(data1) response = requests.post("h ...

Executing a Python script while transferring variables through PHP

Help needed with passing a variable from PHP to Python and displaying it on the webpage. PHP <?php $item='example'; exec("python pytest.py $item"); ?> Python import sys print(sys.argv[1]) Using WAMP, both the PHP and Pytho ...

Changing the story in javascript

I am trying to customize the legend to display the following values: 80+ (or 80%+) 75-80 70-75 65-70 60-65 55-50 <50% While I have organized the list in descending order, I seem to be facing an issue with getting the less than symbol to function correct ...

Group JSON data in Python based on the individuals' last names

Hey there, I'm new to this. How can I manipulate a Json data in Python to create a new format where the last name is used as the key and the value contains the total count of people with the same last name, along with their respective age and departme ...

Can you find a solution using the GUI interface?

Hello, I am currently working on a program to confirm pregnancy using hormone levels (HCG as an integer parameter in a dictionary). However, when testing the GUI, I encountered the following error: "TypeError: string indices must be integers" while checkin ...

What's the best way to combine these date entries into monthly groups?

I am currently working with multiple CSV files containing dataframes for COVID cases. An example of the data looks like this: Region active Date 2020-03-20 Tabuk 1 2020-03-21 Tabuk 1 2020-03-22 Tabuk 1 2020-03-23 Tabuk 1 2020-03-24 ...

Sending emails with PySpark and attaching a CSV file can be done easily. However, you may encounter a common issue

I need assistance with a script I have that generates a DataFrame, converts it to a CSV file, then sends it as an email attachment. The issue I'm facing is that the header and data are all in the first row, resulting in a CSV file with 60k columns and ...

What is the best way to use facepy to find out the gender of my friends?

Attempting to execute the following FQL query: print graph.fql('SELECT name FROM user WHERE gender =male ') Resulted in the following error : OAuthError: [602] (#602) gender is not a member of the user table. I have already included them in f ...

What is the process for choosing a document from a Google Drive pop-up selection window using Python's selenium module?

Currently, I am working on a beta proof of concept automation project where my main focus is entering a Google Drive pop-up window and selecting a specific document to submit. The appearance of the popup window can be seen below: https://i.stack.imgur.com ...

The Excel file is unable to be read because of issues related to "embedded null characters"

Upon opening the Excel file, I encountered the error message "File Format and Extension Don’t Match," which seems to be related to this issue. My attempt to read the file using pandas resulted in an error stating "embedded null character." file_path = r ...

Initiate a Python reboot script within a separate command prompt's window

Is there a way to restart a different script in a separate shell? I have a script that sometimes gets stuck waiting to read email from Gmail and IMAP. From another script, I would like to restart the main one without interrupting the second script's e ...

Transfer the folder from the DBFS location to the user's workspace directory within Azure Databricks

I am in need of transferring a group of files (Python or Scala) from a DBFS location to my user workspace directory for testing purposes. Uploading each file individually to the user workspace directory is quite cumbersome. Is there a way to easily move f ...

What is the best way to eliminate spaces following characters in Python?

In the program, the first line specifies the number of test cases while subsequent lines contain the test cases themselves. Each test case consists of 8 numbers: day1 hour1 min1 sec1 day2 hour2 min2 sec2 (where the second timestamp is always later than the ...