0

I'm looking for a way using python to copy the first column from a csv into an empty file. I'm trying to learn python so any help would be great!

So if this is test.csv

A 32
D 21
C 2
B 20

I want this output

A
D
C
B

I've tried the following commands in python but the output file is empty

f= open("test.csv",'r')

 import csv

reader = csv.reader(f,delimiter="\t")

names=""

for each_line in reader:

    names=each_line[0]
1
  • 1
    Are you writing what you read from the first file to another file at any point? If so, could you include that code as well? Commented Jun 1, 2016 at 16:11

4 Answers 4

1

First, you want to open your files. A good practice is to use the with statement (that, technically speaking, introduces a context manager) so that when your code exits from the with block all the files are automatically closed

with open('test.csv') as inpfile, open('out.csv', 'w') as outfile:

next you want a loop on the lines of the input file (note the indentation, we are inside the with block), line splitting is automatic when you read a text file with lines separated by newlines…

    for line in inpfile:

each line is a string, but you think of it as two fields separated by white space — this situation is so common that strings have a method to deal with this situation (note again the increasing indent, we are in the for loop block)

        fields = line.split()

by default .split() splits on white space, but you can use, e.g., split(',') to split on commas, etc — that said, fields is a list of strings, for your first record it is equal to ['A', '32'] and you want to output just the first field in this list… for this purpose a file object has the .write() method, that writes a string, just a string, to the file, and fields[0] IS a string, but we have to add a newline character to it because, in this respect, .write() is different from print().

        outfile.write(fields[0]+'\n')

That's all, but if you omit my comments it's 4 lines of code

with open('test.csv') as inpfile, open('out.csv', 'w') as outfile:
    for line in inpfile:
        fields = line.split()
        outfile.write(fields[0]+'\n')

When you are done with learning (some) Python, ask for an explanation of this...

with open('test.csv') as ifl, open('out.csv', 'w') as ofl:
    ofl.write('\n'.join(line.split()[0] for line in ifl))

Addendum

The csv module in such a simple case adds the additional conveniences of

  1. auto-splitting each line into a list of strings
  2. taking care of the details of output (newlines, etc)

and when learning Python it's more fruitful to see how these steps can be done using the bare language, or at least that it is my opinion…

The situation is different when your data file is complex, has headers, has quoted strings possibly containing quoted delimiters etc etc, in those cases the use of csv is recommended, as it takes into account all the gory details. For complex data analisys requirements you will need other packages, not included in the standard library, e.g., numpy and pandas, but that is another story.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this worked well and your explanation was really helpful!
0

This answer reads the CSV file, understanding a column to be demarked by a space character. You have to add the header=None otherwise the first row will be taken to be the header / names of columns.

ss is a slice - the 0th column, taking all rows as denoted by :

The last line writes the slice to a new filename.

import pandas as pd

df = pd.read_csv('test.csv', sep=' ', header=None)
ss = df.ix[:, 0]
ss.to_csv('new_path.csv', sep=' ', index=False)

3 Comments

Some more details would be welcomed, since the OP specified he's trying to learn Python.
No need to even slice, just use usecols=[0] in read_csv. And for to_csv you probably want header=False too.
OP is trying to learn Python and you are trying to teach them Pandas!
0
import csv

reader = csv.reader(open("test.csv","rb"), delimiter='\t')
writer = csv.writer(open("output.csv","wb"))

for e in reader:
    writer.writerow(e[0])

2 Comments

Your answer is on the Low Quality Posts Review quee, because of its length and lack of context, and it's a pity because yours is the correct answer. Myself, I'd like to upvote it but I recognize that, as an answer to a learner, it lacks a bit of fleshing around its core.
I'm aiming for a more effective StackSort implementation. Only way to get there is one pure code answer at a time.
0

The best you can do is create a empty list and append the column and then write that new list into another csv for example:

import csv

def writetocsv(l):
#convert the set to the list
b = list(l)
print (b)
with open("newfile.csv",'w',newline='',) as f:
        w = csv.writer(f, delimiter=',')
        for value in b:
             w.writerow([value])

adcb_list = []

f= open("test.csv",'r')
reader = csv.reader(f,delimiter="\t")
for each_line in reader:
              adcb_list.append(each_line)
writetocsv(adcb_list)

hope this works for you :-)

3 Comments

Your function confuses me. Firstly there's an issue with your indentation, then you have a stray apostrophe that comments out part of the code. But I really don't get the purpose of b in all of this... Note also that you can use csv.writerows which will iterate through the list for you.
sorry for the indentation I just press control+k to add code but don't know a shorcut key for indent and that function help me at least with my problem.
You can edit your answer and manually fix the indentation using blocks of 4 spaces. It's important that you make sure that your answers are usable, don't abandon it because a shortcut failed. But even if you fix the indentation, where in your code do you isolate row 0 from row 1 as was asked? I think this has been copy/pasted from your own code somewhere - you're passing a list to writetocsv which makes b superfluous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.