Cut data from one sheet into another in csv in python - python

I am working on a simple program to open a file and read certain rows and then print them in another new file but I want to cut them and remove them from the earlier csv. how do I do that?. This is what I have tried.
import csv
f = open('1.csv')
csv_f = csv.reader(f)
content_value = []
for row in csv_f:
if 'yepme' in row[2]:
content_value.append(row)
g = open('output.csv', 'wb')
wr = csv.writer(g, dialect='excel')
wr.writerows(content_value)
I am editing and found the answer:
import csv
f = open('1.csv')
csv_f = csv.reader(f)
content_value = []
old_value = []
for row in csv_f:
if 'yepme' in row[2]:
content_value.append(row)
else:
old_value.append(row)
g = open('output.csv', 'wb')
wr = csv.writer(g, dialect='excel')
wr.writerows(content_value)
h = open('2.csv','wb')
ws = csv.writer(h, dialect='excel')
ws.writerows(old_value)

A similar problem is mentioned in this question.
Short solution: Write two files: One with the extracted lines, one with the leftovers.
Coded solution:
import csv
with open('1.csv', 'r') as f:
csv_f = csv.reader(f)
new_content = []
old_content = []
for row in csv_f:
if 'yepme' in row[2]:
new_content.append(row)
else:
old_content.append(row)
with open('output.csv', 'wb') as f:
wr = csv.writer(f, dialect='excel')
wr.writerows(new_content)
with open('1.csv', 'wb') as f:
wr = csv.writer(f, dialect='excel')
f.writerows(old_content)
I never used csv, but you should get the idea. If your csv-file is very huge, you should probably read and write line-by-line to avoid memory issues.

Related

How to convert a list into a csv file?

I'm trying to write csv file from a list:
list:
newest = ['x11;y11;z11', 'x12;y12;z12', 'x13;y13;z13', 'x14;y14;z14', 'x15;y15;z15', 'x16;y16;z16', 'x17;y17;z17', 'x18;y18;z18', 'x19;y19;z19', 'x20;y20;z20']
My actual code:
with open(r'listtocsv.csv', 'w', newline='\n') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL, delimiter=';')
wr.writerow(newest)
My actual result:
Result wanted:
import csv
newest = ['x11;y11;z11', 'x12;y12;z12', 'x13;y13;z13', 'x14;y14;z14', 'x15;y15;z15', 'x16;y16;z16', 'x17;y17;z17', 'x18;y18;z18', 'x19;y19;z19', 'x20;y20;z20']
new = []
for i in newest:
new.append(i.split(";"))
with open("file.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(new)
output:

converting TXT to CSV python

I have a txt data. it looks as follows
time pos
0.02 1
0.1 2
...
and so on. so the each line is separated with a space. I need to convert it in to a CSV file. like
time,pos
0.02,1
0.1,2
0.15,3
How can I do it with python ? This is what I have tried
time = []
pos = []
def get_data(filename):
with open(filename, 'r') as csvfile:
csvFileReader = csv.reader(csvfile)
next(csvFileReader)
for row in csvFileReader:
time.append((row[0].split(' ')[0]))
pos.append((row[1]))
return
with open(filename) as infile, open('outfile.csv','w') as outfile:
for line in infile:
outfile.write(line.replace(' ',','))
From here:
import csv
with open(filename, newline='') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
print(row)
For writing just use default options and it would save file with comma as a delimiter.
try:
import pandas as pd
with open(filename, 'r') as fo:
data = fo.readlines()
for d in range(len(data)):
if d==0:
column_headings = data[d].split()
data_to_insert = data[d].split()
pd.DataFrame(data_to_insert).to_excel('csv_file.csv', header=False, index=False, columns = column_headings))
You can use this:
import csv
time = []
pos = []
def get_data(filename):
with open(filename, 'r') as csvfile:
csvfile1 = csv.reader(csvfile, delimiter=' ')
with open(filename.replace('.txt','.csv'), 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for row in csvfile1:
writer.writerow(row)

csv value modification for certain cells on odd rows on a particular column

Hi I'm trying to finish this small piece of code for modifying csv files, I've got this far with some help:
edit... some more info.
Basically what I’m looking to do is make some small changes to the csv file depending on the project and parent issue in JIRA. Python will then make the changes to the csv file before it is then read into JIRA - that’s the second part of the program I’ve not even really looked at yet.
I’m only looking to change the BOX-123 type cells and leave the blank ones blank.
But the idea of the program is that I can use it to make some small changes to a template which will then automatically create some issues in JIRA.
import os
import csv
project = 'Dudgeon'
parent = 'BOX-111'
rows = (1,1007)
current = os.getcwd()
filename = 'test.csv'
filepath = os.path.join(os.getcwd(), filename)
#print(current)
#print(filename)
print(filepath)
with open(filepath, 'r') as csvfile:
readCSV = csv.reader(csvfile)
next(readCSV, None)
for row in readCSV:
print(row[16])
row_count =sum(1 for row in readCSV)
print(row_count)
with open(filepath, 'r') as infile, open('out.csv', 'w') as outfile:
outfile.write(infile.readline()) # write out the 1st line
for line in infile:
cols = line.strip().split(',')
cols[16] = project
outfile.write(','.join(cols) + '\n')
with open('out.csv', 'r') as infile, open('out1.csv', 'w') as outfile:
for row in infile:
if row % 2 != 0:
cols [15] = parent
outfile.write()
Any help really appreciated.
You want to use the row's index when comparing to 0. Use enumerate():
with open('out.csv', 'r') as infile, open('out1.csv', 'w') as outfile:
for rowidx,row in enumerate(infile):
cols = row.strip().split(',')
if rowidx % 2 != 0:
cols[15] = parent
outfile.write(cols)
You really should be using the csv module here, though. Untested but should get you started.
with open('out.csv', 'r') as infile, open('out1.csv', 'w') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for rowidx,row in enumerate(reader):
if rowidx % 2 != 0:
row[15] = parent
writer.write_row(row)
A friend helped me last night and this is what they came up with:
with open(filepath, 'r') as infile, open('out.csv', 'w') as outfile:
outfile.write(infile.readline()) # write out the 1st line
for line in infile:
cols = line.strip().split(',')
cols[16] = project
outfile.write(','.join(cols) + '\n')
with open('out.csv', 'r') as infile, open('out1.csv', 'w') as outfile:
outfile.write(infile.readline()) # write out the 1st line
lineCounter = 0
for line in infile:
lineCounter += 1
cols = line.strip().split(',')
if lineCounter % 2 != 0:
cols[15] = parent
outfile.write(','.join(cols) + '\n')

Adding a column in csv using python

I have hundreds of .csv files with 40 rows and 34 columns each. I want to add a column at position 26 and column 26-34 should shift to make space for the new one. First row of the file is empty and second row has the titles and rest have the values. The new column should have a title in row two and rest of the rows can be zero.
Please help me with this code in python.
import csv
infilename = r'C:\Users\Sulabh Kumra\Desktop\input.csv'
outfilename = r'C:\Users\Sulabh Kumra\Desktop\output.csv'
with open(infilename, 'rb') as fp_in, open(outfilename, 'wb') as fp_out:
reader = csv.reader(fp_in, delimiter=",")
headers = next(reader) # read first row
writer = csv.writer(fp_out, delimiter=",")
writer.writerow(headers)
for row in reader:
row.append(row[2])
writer.writerow(row)
Inserting into a python list is pretty easy: some_list[2:2] = ['stuff','to','insert']
So your code would look like the following:
import csv
infilename = r'C:\Users\Sulabh Kumra\Desktop\input.csv'
outfilename = r'C:\Users\Sulabh Kumra\Desktop\output.csv'
with open(infilename, 'rb') as fp_in, open(outfilename, 'wb') as fp_out:
reader = csv.reader(fp_in, delimiter=",")
writer = csv.writer(fp_out, delimiter=",")
blank_line = next(reader)
writer.writerow(blank_line)
headers = next(reader) # read title row
headers[26:26] = ['New Label']
writer.writerow(headers)
for row in reader:
row[26:26] = [0]
writer.writerow(row)

Taking data from text file and writing it as a .csv file in python

EDIT: Thanks for the answers guys, got what I needed!!
Basically I am trying to take what I have stored in my textfile and I am trying to write that into a .csv file. In my file are tweets that I have stored and I am trying to have one tweet in each cell in my .csv file.
Right now it is only taking one tweet and creating a .csv file with it and I need it to take all of them. Any help is greatly appreciated. Here is what I have so far.
with open('reddit.txt', 'rb') as f:
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
for row in reader:
print row
cr = csv.writer(open('reddit.csv', 'wb'))
cr.writerow(row)
You'll need to create the writer outside of the loop:
with open('reddit.txt', 'rb') as input_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
with open('reddit.csv', 'wb') as output_file:
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
Although here it might be cleaner to open the files without with:
input_file = open('reddit.txt', 'rb')
output_file = open('reddit.csv', 'wb')
reader = csv.reader(input_file, delimiter=':', quoting=csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
input_file.close()
output_file.close()
Or you can still use with and just have a really long line:
with open('reddit.txt', 'rb') as input_file, open('reddit.csv', 'wb') as output_file:
reader = csv.reader(input_file, delimiter=':', quoting = csv.QUOTE_NONE)
writer = csv.writer(output_file)
for row in reader:
writer.writerow(row)
The line cr = csv.writer(open('reddit.csv', 'wb')) is inside the for loop. You need to open the file just once, place this line after
reader = csv.reader(f, delimiter=':', quoting = csv.QUOTE_NONE)
Then write to it as you did in each loop iteration.

Categories

Resources