-1

I have the codez:

import re

pattern  = ','
firstNames = "dictionary//first_names.txt"
new_file = []

def openTxtFile(txtFile):
    file = open (txtFile,"r")

data = file.read()

print (data)

file.close

def parseTextFile(textFile):

    openTxtFile(firstNames)

for line in lines:

    match = re.search(pattern, line)
        if match:

        new_line = match.group() + '\n'
        print (new_line)
        new_file.append(new_line)

with open(firstNames, 'w') as f:

f.seek(0)

f.writelines(new_file)

I am trying to take the original file, match it on a "," and return line by line to a New file the string before the "," I'm having trouble putting all this together, thanks!

3
  • 1
    Please format/indent your code properly. Commented Nov 18, 2013 at 2:29
  • why not just line.split(',')[0] instead of a regular expression? Commented Nov 18, 2013 at 2:32
  • Yeah the split would work, but I have a LOT of names to do this to, I was thinking regex would be faster.
    – Adam
    Commented Nov 18, 2013 at 4:15

1 Answer 1

1

Use the csv module, since your original file is comma separated:

import csv

with open('input_file.txt') as f:
   reader = csv.reader(f)
   names = [line[0] for line in reader]

with open('new_file.txt','w') as f:
   for name in names:
      f.write('{0}\n'.format(name))
1
  • The original file is a csv file that I was putting into a .txt file. I'm guessing then the csv will be easier to take care of then? So I don't need to split or manipulate the string at all, just the {0} location will give me the 1st element from each row in the csv file?
    – Adam
    Commented Nov 18, 2013 at 4:28

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.