简体   繁体   中英

How to read file line by line abd write it to file based on condition. in python

I want to read file line by line first perform some operation on first value then want to read second value from file again want to perform some operation Eg.if I have one file which have values Vik John Lisa

I want to read one by one and pass to sql server and write the output(age) based on gender in file If name started with Vik is male then write his age in file male.txt else female.txt Could you please help me on this

code :

with open('C:\code\out.txt', 'r') as content_file:
  for line in content_file:
    cs=pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server}',server = '.', database = 'Test')
    tablequery="select Age,Gender from dbo.AuditSource where Name='" + line+"'";
    cursor = cs.cursor()
    cursor.execute(tablequery)
    rows = cursor.fetchall()
    for row in rows:
        age=row.Age
        Gen=row.Gender
        print(age)
        if Gen=='M':
            with open('C:\code\male.txt', 'a') as f:
                f.write(age) #here getting error not able toe write var value

        else:
            with open('C:\code\female.txt', 'a') as f:
                f.write(age) #here getting error not able toe write var value

This is the code what you are asking.

search = open("some.txt","r") #opens and read file        
for line in search:
   new  = line[0]
   if new == "V":
      file = open("edit.txt","w")
      file.write(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM