-4

I have a python file where I get user inputs for student database and I have written them as a csv file. I couldn't get the links in google to read the csv output and write those csv output to a text file.

Sample Csv output:

Name    Roll no Age Mark1   Mark2
a        1       2    3       4
g        3      54    54      3

import csv

with open('abc.csv','r') as f:
    reader=csv.dictreader(f)
    for row in reader:
        output=('xyz.txt','r')

I know how to read a csv file but I don't know how to write those contents to a text file

6
  • 1
    please google your question first Commented May 5, 2017 at 9:21
  • Possible duplicate of Python script to read a text file and write into a csv file Commented May 5, 2017 at 9:22
  • To all, my question is ow to read the csv output and write it to a text file and not reading text file and writing it to csv Commented May 5, 2017 at 9:31
  • if you believe your question is unique, then please provide your code. show us what you have already done. Commented May 5, 2017 at 9:36
  • so, you want to write each row of csv to the text file 'xyz.txt'? Commented May 5, 2017 at 9:55

3 Answers 3

3

Use the below code Indentation and comments are inline

  1. Read CSV file
  2. Manipulate Fields
  3. Write to file

Blockquote

import csv

#Open file with "w"(write), the file will create automatically.
file = open("/home/xyz/testfile.txt", "w")
#Open CSV file to read CSV, note: reading and write file should be under "with"
with open('/home/xyz/Desktop/ta_cta.csv') as csvFile:
    #Read CSV
    readCsv = csv.reader(csvFile)
    for row in readCsv:
        #Get Values and manupilate in the file.write
        Id = row[0]
        Id1 = row[1]
        #Write CSV you need format it to string if the value is an int
        file.write("UPDATE Schema.TableName SET Column1="+str(Id1)+" where Column2="+str(Id)+";\n")
#You Must Close the FIle after writing it.
file.close()
Sign up to request clarification or add additional context in comments.

Comments

0

you can try this code:

import csv

output=open('xyz.txt','w')

with open('abc.csv',"rt", encoding='ascii') as f:
for row in f:
    output.write(row)

8 Comments

For loop needs to be intended. Ascii encoding wasnt needed for my file. Please edit them.
Can you explain why you gave mode as rt and ascii encoding? I can understand the rest of codes. Sorry I'm a beginner in python
sure, but I bet you can google things, the answer to your question is here:stackoverflow.com/questions/23051062/…
About, ascii encoding, just in case, maybe you will need it.
Thanks :) How to get the contents of entire row in csv file when i select a particular roll no?
|
0

You should learn python csv module firstly.

https://docs.python.org/2/library/csv.html

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.