I can read a text file with names and print in ascending order to console. I simply want to write the sorted names to a column in a CSV file. Can't I take the printed(file) and send to CSV?
Thanks!
import csv
with open('/users/h/documents/pyprojects/boy-names.txt','r') as file:
for file in sorted(file):
print(file, end='')
#the following isn't working.
with open('/users/h/documents/pyprojects/boy-names.csv', 'w', newline='') as csvFile:
names = ['Column1']
writer = csv.writer(names)
print(file)
You can do something like this:
import csv
with open('boy-names.txt', 'rt') as file, open('boy-names.csv', 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL)
csv_writer.writerow(['Column1'])
for boy_name in sorted(file.readlines()):
boy_name = boy_name.rstrip('\n')
print(boy_name)
csv_writer.writerow([boy_name])
This is covered in the documentation.
The only tricky part is converting the lines from the file to a list of 1-element lists.
import csv
with open('/users/h/documents/pyprojects/boy-names.txt','r') as file:
names = [[k.strip()] for k in sorted(file.readlines())]
with open('/users/h/documents/pyprojects/boy-names.csv', 'w', newline='') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(['Column1'])
writer.writerows(names)
So, names will contain (for example):
[['Able'],['Baker'],['Charlie'],['Delta']]
The CSV recorder expects to write a row or a set of rows. EACH ROW has to be a list (or tuple). That's why I created it like I did. By calling writerows, the outer list contains the set of rows to be written. Each element of the outer list is a row. I want each row to contain one item, so each is a one element list.
If I had created this:
['Able','Baker','Charlie','Delta']
then writerows would have treated each string as a sequence, resulting in a CSV file like this:
A,b,l,e
B,a,k,e,r
C,h,a,r,l,i,e
D,e,l,t,a
which is amusing but not very useful. And I know that because I did it while I was creating your answer.
Related
I have below code to write my nested list into a csv file. The nested list looks like this
[['19181011', '13041519', '22121605', '11142007', '23000114'],
['1523141612', '2403051513', '0806022324', '1614012422', '0516121805'],
['23201621', '24171811', '08231524', '16011022', '17131220'],
['2317241822', '2220112421', '1124052211', '1010192318', '2108231524'],
['11220215', '24240507', '19180423', '07081422', '21201224']]
with open('MLpredictions.csv', 'w') as f:
writer = csv.writer(f, delimiter=';', lineterminator='\n')
writer.writerows(high5_pred)
But when i execute this code, i get like below in the csv file:
19181011;13041519;22121605;11142007;23000114
1523141612;2403051513;0806022324;1614012422;0516121805....
i changed the delimiter to ',' but then I get 5 different columns.
I want each list to be 1 row separated by ',' and not ';'.
Expected o/p, a single column:
19181011,13041519,22121605,11142007,23000114
1523141612,2403051513,0806022324,1614012422,0516121805
Any ideas how to do this?
Assuming that there is a specific reason why you want the data all in one column:
The reason you're getting seperate columns is because you're using the csv format, and your data is not escaped. Your raw file looks like this:
19181011,13041519,22121605,11142007,23000114
1523141612,2403051513,0806022324,1614012422,0516121805
but you need it to look like this:
"19181011,13041519,22121605,11142007,23000114"
"1523141612,2403051513,0806022324,1614012422,0516121805"
You're probably best to create a string object for each "row" of your output file. I'd do the following:
with open('MLpredictions.csv', 'w') as f:
writer = csv.writer(f, delimiter=';', lineterminator='\n')
rows = [','.join([str(number) for number in row]) for row in high5_pred]
writer.writerows(rows)
Note: unless you have a good reason why you don't want these numbers in different columns, I'd leave your code as is. It will be a lot easier to deal with the native csv format
So I have a CSV file like this,
how can I separate them into different columns like this,
using python without using the pandas lib.
Implementation that should work in python 3.6+.
import csv
with open("input.csv", newline="") as inputfile:
with open("output.csv", "w", newline="") as outputfile:
reader = csv.DictReader(inputfile) # reader
fieldnames = reader.fieldnames
writer = csv.DictWriter(outputfile, fieldnames=fieldnames) # writer
# make header
writer.writeheader()
# loop over each row in input CSV
for row in reader:
# get first column
column: str = str(row[fieldnames[0]])
numbers: list = column.split(",")
if len(numbers) != len(fieldnames):
print("Error: Lengths not equal")
# write row in output CSV
writer.writerow({field: num for field, num in zip(fieldnames, numbers)})
Explanation of the code:
The above code takes two file names input.csv and output.csv. The names being verbose don't need any further explanation.
It reads each row from input.csv and writes corresponding row in output.csv.
The last line is a "dictionary comprehension" combined with zip (similar to "list comprehensions" for lists). It's a nice way to do a lot of stuff in a single line but same code in expanded form looks like:
row = {}
for field, num in zip(fieldnames, numbers):
row[field] = num
writer.writerow(row)
It is already separated into different columns by , as separator, but the european version of excel usually uses ; as separator. You can specify the separator, when you import the csv:
https://support.microsoft.com/en-us/office/import-or-export-text-txt-or-csv-files-5250ac4c-663c-47ce-937b-339e391393ba
If you really want to change the file content with python use the replace function and replace , with ;: How to search and replace text in a file?
I am trying to write the elements of a list (each time I get from a for loop) as individual columns to a CSV file. But the elements are adding as an individual rows, but not columns.
I am new to python. What needs to be changed in my code? Please tell me
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='"')
for item in row:
writer.writerow([item])
But I am getting the output as below:
ABC
XYZ
ABCD
My expected output is a below:
ABC XYZ ABCD
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,
Actually you are writing in different rows, you don't need to do that. You can write your whole list as a single row. You need spaces so for that you can modify your list.
So i have been reading answers on StackOverflow and haven't been able to find this specific doubt that i have.
I have a csv with a single column with values as follows:
**Values**
abc
xyz
bcd,fgh
tew,skdh,fsh
As you can see above some cells have more than one value separated by commas,
i used the following code:
with open('dat.csv', 'rb') as inputfile:
reader = csv.reader(inputfile)
colnames=['Keywords']
data = pandas.read_csv('dat.csv', names=colnames)
lkn=data.values.tolist()
print lkn
The output i got was: [['abc'],['xyz'],['bcd,fgh'],['tew,skdh,fsh']]
i would like to have the output as:
[['abc'],['xyz'],['bcd','fgh'],['tew','skdh','fsh']]
which i believe is a proper list of list format(fairly new to list of lists). Please do provide guidance in the right direction.
Thanks!.
NB:csv file with how cells are arranged (image)
Looking at your attached image, I'd bet that the cells have been quoted (although, to be sure, open the CSV file in a text editor, not in Excel) so you have to do the manual splitting yourself:
import csv
with open("file.csv", "r") as f:
reader = csv.reader(f)
your_list = [e[0].strip().split(",") for e in reader if e]
Try something like this :
import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
your_list = list(reader)
for item in your_list:
item = list(item)
print(your_list)
Credit : Python import csv to list
I am trying to "clean up" some data - I'm creating a dictionary of the channels that I need to keep and then I've got an if block to create a second dictionary with the correct rounding.
Dictionary looks like this:
{'time, s': (imported array), 'x temp, C':(imported array),
'x pressure, kPa': (diff. imported array).....etc}
Each imported array is 1-d.
I was looking at this example, but I didn't quite get the way to parse it so that I ended up with what I want.
My desired output is a csv file (do not care if the delimiter is spaces or commas or whatever) with the first row being the keys and the subsequent rows simply being the values.
I feel like what I'm missing is how to use the map function properly.
Also, I'm wondering if I'm using DictWriter when I should be using DictReader.
This is what I originally tried:
with open((filename), 'wb') as outfile:
write = csv.DictWriter(outfile, Fieldname_order)
write.writer.writerow(Fieldname_order)
write.writerows(data)
DictWriter's API doesn't match the data structure you have. DictWriter requires list of dictionaries. You have a dictionary of lists.
You can use the ordinary csv.writer:
my_data = {'time, s': [0,1,2,3], 'x temp, C':[0,10,20,30],
'x pressure, kPa': [0,100,200,300]}
import csv
with open('outfile.csv', 'w') as outfile:
writer = csv.writer(outfile)
writer.writerow(my_data.keys())
writer.writerows(zip(*my_data.values()))
That will write the columns in arbitrary order, which order may change from run to run. One way to make the order to be consistent is to replace the last two lines with:
writer.writerow(sorted(my_data.keys()))
writer.writerows(zip(*(my_data[k] for k in sorted(my_data.keys()))))
Edit: in this example data is a list of dictionaries. Each row in the csv contains one value for each key.
To write your dictionary with a header row and then data rows:
with open(filename, 'wb') as outfile:
writer = csv.DictWriter(outfile, fieldnames)
writer.writeheader()
writer.writerows(data)
To read in data as a dictionary then you do need to use DictReader:
with open(filename, 'r') as infile:
reader = csv.DictReader(infile)
data = [row for row in reader]