I have a CSV file contains data reviews and I want to append it to list.
Here is a sample in my file.csv:
I love eating them and they are good for watching TV and looking at movies
This taffy is so good. It is very soft and chewy
I want save in a list all the words of the second line and print them:
['This', 'taffy', 'is', 'so', 'good.', 'It', 'is', 'very', 'soft', 'and', 'chewy']
I tried this:
import csv
with open('file.csv', 'r') as csvfile:
data = csv.reader(csvfile, delimiter=',')
texts = []
next(data)
for row in data:
texts.append(row[2])
print(texts)
My problem is it doesn't print anythings. Can anyone help here?.. Thanks in advance
Don't forget to import csv, if you want to save all the words in the second line, you have to enumerate the lines and take what you want, after that split them and save it in the list, like this:
import csv
texts = []
with open('csvfile.csv', 'r') as csvfile:
for i, line in enumerate(csvfile):
if i == 1:
for word in line.split():
texts.append(word)
print(texts)
$['This', 'taffy', 'is', 'so', 'good.', 'It', 'is', 'very', 'soft', 'and', 'chewy']
Related
I would like to to write dictionary to a csv file with one line for every 'key: value' and serial number of keys?
import csv
dict = {"(2,3,4)" : '3', "(201,233,207)" : '23', "(176,247,207)" : '78'}
w = csv.writer(open("data.csv", "w"))
w.writerow(['xval'+ "\t" + 'yval'])
for key, val in dict.items():
w.writerow([str(key)+ "\t" + str(val)])
It creates :
It does not creates tab separated columns. I want tab separated columns and also a extra column with a serial number.
Added:
CSV data sheet looks like this:
Do not add '\t' yourself. Instead, use the delimiterargument of csv.writer.
As a bonus, this code:
Uses with
Cleans all the conversions to str with map
Opens the file with newline='' becuase csv.writer tends to add line breaks
import csv
d = {"(2,3,4)": '3', "(201,233,207)": '23', "(176,247,207)": '78'}
with open("data.csv", "w", newline='') as f:
w = csv.writer(f, delimiter='\t')
w.writerow(map(str, (0, 'xval', 'yval')))
for counter, (key, val) in enumerate(d.items(), 1):
w.writerow(map(str, (counter, key, val)))
When opening the file in Excel or any other spreadsheet application make sure to choose tabs as the delimiter.
I haven't used Python 2.7 in ages. I hope this does not terribly fail.
I have a folder where a store files from my fitting model in .txt format.
My question here is how to write a loop which will take e.g p1_cen 7.65782003 from this file and append it to a column in a .csv file?
The other thing with my question is that number of those files is equal to 288, because I store 5 minute long data from each day. And a loop what I need is to take from those 288 files a specifit data e.g like above, do You have any ideas how to do this?
For now, I have this code, which writes data in .txt files from my lmfit model.
with open('S:\Doc\Python\Results\DecompositionBx ' + "{0}".format(Station) + "{0}{1}".format(Start_time_hours_format, Start_time_minutes_format) + ".txt", 'w') as fh:
fh.write(result.fit_report(show_correl=False))
Btw. my files are named accordingly
DecompositionBxHylaty0000
...
DecompositionBxHylaty2355
UPDATE!!!
So the code from #bobrobbob works:
import csv
from datetime import timedelta
data = []
for i in range(288):
skip = i*timedelta(minutes=5)
hours, minutes, _ = str(skip).split(':')
filename = "S:\Dok\Python\Results\DecompositionBx Hylaty%02d%02d.txt" % (int(hours), int(minutes))
with open(filename) as f:
lines = f.readlines()
for line in lines:
if line.startswith(' p1_cen'):
data.append(line.split('+')[0])
break
with open('S:\Dok\Python\Results\data.csv', 'w') as f:
writer = csv.writer(f)
for line in data:
writer.writerow(line)
I get something like this, which is nearly perfect:
a bit ugly on the time handling, maybe someone will come with a cleaner solution. but it should work nonetheless
import csv
from datetime import timedelta
data = []
for i in range(288):
skip = i*timedelta(minutes=5)
hours, minutes, _ = str(skip).split(':')
filename = "DecompositionBxHylaty%02d%02d" % (int(hours), int(minutes))
with open(filename) as f:
lines = f.readlines()
for line in lines:
if line.startswith('p1_cen'):
data.append(line.split('+')[0].strip())
break
with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f, delimiter=' ')
for line in data:
writer.writerow(line.split())
I wrote a very simple program that was supposed to read a CSV and print all of the rows twice. However, when I ran the program, it printed all of the rows the first time, and nothing the second time.
Code:
import csv
csvfile = csv.reader(open(<path>, 'rb'))
print 'Attempt 1'
for row in csvfile:
print row
print 'Attempt 2'
for row in csvfile:
print row
Output:
Attempt 1
['a', 'b', 'c']
['d', 'e', 'f']
Attempt 2
Why is the code not printing the contents again the second time?
You need to rewind the open file:
import csv
csvfile = csv.reader(open(<path>, 'rb'))
print 'Attempt 1'
for row in csvfile:
print row
csvfile.seek(0, 0)
print 'Attempt 2'
for row in csvfile:
print row
This way it should work fine.
Correct me if I'm wrong but I'm pretty sure the csvfile variable you create is a generator object.
Generators are not stored in memory but can only be iterated over once!
Hope this helps,
Luke
I want to replace one specific word, 'my' with 'your'. But seems my code can only change one appearance.
import csv
path1 = "/home/bankdata/levelout.csv"
path2 = "/home/bankdata/leveloutmodify.csv"
in_file = open(path1,"rb")
reader = csv.reader(in_file)
out_file = open(path2,"wb")
writer = csv.writer(out_file)
with open(path1, 'r') as csv_file:
csvreader = csv.reader(csv_file)
col_count = 0
for row in csvreader:
while row[col_count] == 'my':
print 'my is used'
row[col_count] = 'your'
#writer.writerow(row[col_count])
writer.writerow(row)
col_count +=1
let's say the sentences is
'my book is gone and my bag is missing'
the output is
your book is gone and my bag is missing
the second thing is I want to make it appear without comma separated:
print row
the output is
your,book,is,gone,and,my,bag,is,missing,
for the second problem, im still trying to find the correct one as it keeps giving me the same output with comma separated.
with open(path1) as infile, open(path2, "w") as outfile:
for row in infile:
outfile.write(row.replace(",", ""))
print row
it gives me the result:
your,book,is,gone,and,my,bag,is,missing
I send out this sentence to my Nao robot and the robot seems pronouncing awkwardly as there are commas in between each word.
I solved it by:
with open(path1) as infile, open(path2, "w") as outfile:
for row in infile:
outfile.write(row.replace(",", ""))
with open(path2) as out:
for row in out:
print row
It gives me what I want:
your book is gone and your bag is missing too
However, any better way to do it?
I open the folder and then I tried to tokenize each word in the CSV file. Is this code correct? I tried to read the file and then tokenize, but I cannot see the result. I am new in programming, can some one help me with it?
filename=open("positivecsv.csv","r")
type(raw) #str
tokens = []
for line in filename.readlines():
tokens+=nltk.word_tokenize(line)
>>> print tokens
Python has a built-in CVS reader and writer
, so you need to do it yourself.
Here is an example:
import csv
with open('positivecsv.csv', 'r') as csvfile: # this will close the file automatically.
reader = csv.reader(csvfile)
for row in reader:
print row
Row will be a list which contains all elements of the current line.