Writing Python lists to columns in csv
Change them to rows:
rows = zip(list1, list2, list3, list4, list5)
Then just:
import csv
with open(newfilePath, "w") as f:
writer = csv.writer(f)
for row in rows:
writer.writerow(row)
Writing a Python list into a single CSV column
With Python3, open the file in w
mode:
with open('returns.csv', 'w') as f:
writer = csv.writer(f)
for val in daily_returns:
writer.writerow([val])
With Python2.6+, open the file in wb
mode:
with open('returns.csv', 'wb') as f:
writer = csv.writer(f)
for val in daily_returns:
writer.writerow([val])
How to turn a list into a column in a csv?
To perform this task I would use pandas
package as follows:
import pandas as pd
l=["a","b","c","d"]
df=pd.DataFrame(l,index=False,header=False)
df.to_csv("twitter3.csv")
pandas
is also great to read csv and even work with Excel files.
Write a list of values as separate columns to a CSV file using Python
You are iterating over the list row
and writing each element as a new row in your code when you do writer.writerow([item])
.
Instead you want to write the entire row in one line using writer.writerow
import csv
row=['ABC','XYZ','','','ABCD',''] #my list looks like this every time
with open('some.csv', 'w') as writeFile:
writer = csv.writer(writeFile, delimiter=',', quotechar='"')
#Write the list in one row
writer.writerow(row)
The file will look like
ABC,XYZ,,,ABCD,
Write list of lists to CSV file. Putting sub-lists into individual columns
Use following code snippet:
import pandas as pd
cols = ['a', 'b', 'c', 'd']
d = [dict(zip(cols, vals)) for vals in results]
pd.DataFrame(d).to_csv('C:\Users\out.csv')
In case you want to append to existing csv file, change last line to:
pd.DataFrame(d).to_csv('C:\Users\out.csv', mode='a', header=False)
This is how your dataframe looks:
a b c d
0 11 22 33 [1, 2, 3]
1 44 55 66 [4, 5, 6]
A Way To Store Unknown Amount Of Separate Lists As Columns In A csv File (Python)?
You could try something like:
Step 1: Create file csv file if not already exist
Step 2: Read the csv file to memory
Step 3: Get the user input and append to the data you read from the csv ( can be looped if there are multiple entries to be read)
Step 4: Write back the data (not append but as new file with the same name)
Implementation:
from pathlib import Path
import csv
def read_existing_data(filename):
csv_file = Path(filename)
csv_file.touch(exist_ok=True)
input_data = [row for row in csv.DictReader(open(filename))]
return input_data
def get_user_input():
entry_list = list()
entry = dict()
true = 'yes'
while true:
user_entry = input("Do you want an entry? 'yes' to continue, ('no' to stop): ")
if user_entry == 'no':
break
else:
entry["full_name"] = input("Enter a full name: ")
entry["first_time"] = float(input("Enter first time: "))
entry["second_time"] = float(input("Enter second time: "))
entry["third_time"] = float(input("Enter third time: "))
entry_list.append(entry)
return entry_list
def save_to_file(filename, csv_data):
columns = csv_data[0].keys()
try:
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=columns)
writer.writeheader()
for rows in csv_data:
writer.writerow(rows)
except IOError:
print("I/O error")
file_name = "times.csv"
# Read Existing data
data = read_existing_data(file_name)
# Append new data
data.extend(get_user_input())
# Save to file
save_to_file(file_name, data)
Related Topics
How to Handle Os.System Sigkill Signal Inside Python
Gae " No Attribute 'Httpshandler' " Dev_Appserver.Py
Python Script Prints Output of Os.System Before Print
Subprocess.Popen(): Oserror: [Errno 8] Exec Format Error in Python
Why Does Simple Echo in Subprocess Not Working
How to Determine Pid of Process Started via Os.System
Better Way to Script Usb Device Mount in Linux
Linux/Python: Encoding a Unicode String for Print
Pyserial Works Fine in Python Interpreter, But Not Standalone
Running Python Script as a Systemd Service
/Usr/Bin/Env: Python2: No Such File or Directory
How to Integrate Ajax With Django Applications
How Does Collections.Defaultdict Work
How to Recover the Return Value of a Function Passed to Multiprocessing.Process