I have list like the one below,
lista=["a","b","c","\n","d","e","f","\n","g","h","i","\n"]
Can some one please advise how I make csv module to write this so that every "\n" in the list is counted as a line break? To make it simpler the csv should look like this,
a,b,c
d,e,f
g,h,i
Please let me know if the question is not clear, I will make changes as required.
import csv
import sys
def rows(lst):
it = iter(lst)
while True:
row = list(iter(it.next, '\n')) # it.__next__ in Python 3.x
if not row:
break
yield row
lista = ["a","b","c","\n","d","e","f","\n","g","h","i","\n"]
writer = csv.writer(sys.stdout) # Replace sys.stdout with file object
writer.writerows(rows(lista))
You don't really need the CSV module:
for s in ','.join(lista).split('\n'):
print(s.strip(','), '\n')
This gives:
a,b,c
d,e,f
g,h,i
Related
I have a csv file which is a list as seen here:
A
B
C
D
E
F
And I would like to transform it into a list with pair like this:
AB
CD
EF
What is simplest way to achieve this?
An alternative approach using itertools.islice, it will avoid reading the whole file at once:
import csv
from itertools import islice
CHUNK = 2
def chunks():
with open("test.csv", newline="") as f:
reader = csv.reader(f)
while chunk := tuple(islice(reader, CHUNK)):
yield "".join(*zip(*chunk))
def main():
print(list(chunks()))
if __name__ == "__main__":
main()
Note:
The walrus operator (:=) is available since Python 3.8+, in previous versions you'll need something like this:
chunk = tuple(islice(reader, CHUNK))
while chunk:
yield "".join(*zip(*chunk))
chunk = tuple(islice(reader, CHUNK))
The easiest way is probably to put each line of your file in a list and then create a list with half the size and your pairs. Since your .csv file appears to have only one column, the file format doesn't really matter.
Now, I assume that you have the file eggs.csv in the same directory as your Python file:
A
B
C
D
E
F
The following code produces the expected output:
output_lines = []
with open('eggs.csv', 'r') as file:
for first, second in zip(file, file):
output_lines.append(f'{first.strip()}{second.strip()}')
If you execute this code and print output_lines, you will get
['AB', 'CD', 'EF']
Note that if the number of lines is odd, the last line will be simply ignored. I don't know the desired behavior so I just assumed this, but you can easily change the code.
Here's my code:
f = open("cities.txt", 'wb')
pickle.dump(city_list, f)
f.close()
I know normally to print a list vertically, into new lines, you do this inside a print statement: print(*city_list, sep='\n'). I want to know if there's a way to do this when creating the pickle file, so that when you open it, you see a vertical list, without having to do anything else. For example, when I open the file:
fh = open("cities.txt", 'rb')
x = pickle.load(fh)
print(x)
I want the output to be a vertical list without me having to add a sep='\n' to the print statement.
Once you have loaded your pickled data, it has been converted to a regular Python list already. What you are asking is then: How can I print the items of a list, one item per line?
The answer is simply to do this:
for item in x:
print(item)
If instead you want the output file to be more easily readable by a human, you should encode your data in a format other than what Python's pickling module offers.
Using CSV:
import csv
city_list = [
('Montreal', 'Canada'),
('Belmopan', 'Belize'),
('Monaco', 'Monaco'),
]
with open('cities.txt', 'w') as file:
writer = csv.writer(file)
for city, country in city_list:
writer.writerow(city, country)
This will result in cities.txt containing the following:
Montreal,Canada
Belmopan,Belize
Monaco,Monaco
I want to be able to create two lists: Time and data.
import time
date = [time.strftime("%Y/%m/%d %I:%M%p")]
data = []
x = input()
data.append(x)
with open("RapData.txt", "a") as output:
output.write(str(date))
output.write(str(data))
This code makes the two lists and saves it all on one line in the txt file like this if ran twice:
['2017/06/28 02:15PM']['x']['2017/06/28 02:15PM']['x']
and i want it to be:
['2017/06/28 02:15PM']['2017/06/28 02:15PM']
['x']['x']
You need to write the newline character to the file as well:
import time
date = [time.strftime("%Y/%m/%d %I:%M%p")]
f = open("RapData.txt", "a")
data = [input()]
f.write(str(date))
f.write('\n')
f.write(str(data))
To achieve what you are asking for you can't use append (as append adds items to the end of the file).
You would need to read the data to a local variable and output it to the file again:
open("RapData.txt","r")
... read code...
open("RapData.txt","w")
... write code..
I wrote this program to read a column from an excel file then write it into a txt file:
import xlrd, sys
text_file = open("Output.txt", "w")
isotope = xlrd.open_workbook(sys.argv[1])
first_sheet=isotope.sheet_by_index(0)
x= []
for rownum in range(first_sheet.nrows):
x.append(first_sheet.cell(rownum, 1))
for item in x:
text_file.write("%s\n" % item)
text_file.close()
It reads the column correctly but writes it like so:
number:517.0
number:531.0
number:517.0
number:520.0
number:513.0
number:514.0
number:522.0
Can I read it in a way that it just writes the value and not "number:"? I could just cut out the first 7 characters of every line, but that seems kind of inefficient.
Thanks for the help!
Also, if you want a way to read entire values of a row in one shot:
You can take first_sheet and do:
first_sheet.row_values(index_of_row)
This will return a list with all the values of the index_of_row.
I've a little problem here. I need to read a txt file and store it into a list, I'm already doing that... but the problem is that I need to manipulate some columns like multiplying then by 30 and so forth so on. (I'm still learning python) (Its python 3.4)
The test.txt file:
Abacate;Para;PA;-1.1166667;-49.65
Abacate;Amazonas;AM;-3.9463889;-62.9038889
The code:
def readFile():
with open('test.txt') as f:
reader = csv.reader(f,delimiter=";")
#reader.next()
for row in reader:
for (i,v) in enumerate(row):
columns[i].append(v)
But, when I try to use
for i in range(0,len(columns[3])):
listTest.append(columns[3][i]*3)
The result is:
['-1.1166667-1.1166667-1.1166667']
['-1.1166667-1.1166667-1.1166667', '-3.9463889-3.9463889-3.9463889']
Expected:
['-3.3500001','-11.8391667']
Is there a better way to do this?
Python is reading the numbers as strings, so when you do the *3 it thinks "Ah! Matt wants me to put the the string three times in a row!"
If you just convert it to a float first, it'll be fine:
for i in range(0,len(columns[3])):
listTest.append(float(columns[3][i])*3)
You need to parse the columns[3][i] into float like
listTest.append(float(columns[3][i])*3)
Because
'any_string'*3
>>any_stringany_stringany_string
100*3
>>300
import csv
def readFile(infilepath):
answer = []
with open(infilepath) as infile:
for *_head, a, _b in csv.reader(infile, delimiter';'):
answer.append(float(a) * 3)
return answer