Вопрос:

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

python python-2.7

78 просмотра

1 ответ

1 Репутация автора

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
Автор: Viky Источник Размещён: 11.11.2017 09:55

Ответы (1)


0 плюса

582 Репутация автора

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)
Автор: sachin dubey Размещён: 11.11.2017 10:00
Вопросы из категории :
32x32