0

I have a CSV that looks like this

"String1","variablelengthstring1","No"
"String2","variablelengthstring2","No"

String1 and string2 does NOT contain the characters " or ,

variablelengthstring1 and variablelengthstring2 does NOT contain the characters " or ,

The output file should look like this

String1 variablelengthstring1
String2 variablelengthstring2

So I want to remove the last 6 chars on each line, i.e.
","No"

Then, I want to remove all " from the file

Then, I want to replace all , with a space

That should safely accomplish what I am trying to do

1
  • 1
    What have you tried so far? Please share the code. Commented Dec 30, 2022 at 5:34

1 Answer 1

2

The easiest way is to just create a program that reads the file line by line, splitting each line up with .split(','), removing all "s from the string, then printing the first parts. Like this:

with open('test.csv') as csv:
    for row in csv.readlines():
        cols = [s.replace('"', '') for s in row.split(',')]
        print(cols[0], cols[1])

If you need to output it to a file, then you can use redirection in your command line. Just run the program like this:

python program.py > output.txt

Alternatively, you can use another nested with statement and .writelines(), like this:

lines = []
with open('test.csv') as csv:
    for row in csv.readlines():
        cols = [s.replace('"', '') for s in row.split(',')]
        lines.append(f'{cols[0]} {cols[1]}\n')

with open('out.txt', 'w') as out:
    out.writelines(lines)
Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't depend on console redirection to write it back to a file, should just write it directly. Otherwise yes this works fine.
@kjsmita6 I've updated my answer with an alternative example of writing the lines directly to a file. It should be all good now.
Worked perfectly, thank you. can I arrange in decending order by numerical value of variablelengthstring1
@investome If you need to rearrange the output, then you'll want to first read the CSV into a list, then use the .sort() method. If you need more help with that, you might want to ask another question.

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.