如何逐行读取文件abd根据条件将其写入文件。在python中

时间:2017-11-11 09:55:41

标签: python python-2.7

我想逐行读取文件首先对第一个值执行一些操作然后再想从文件中读取第二个值要执行一些操作 如果我有一个有值的文件 维克 约翰 莉莎

我想逐个阅读并传递给sql server并根据文件中的性别写出输出(年龄) 如果以Vik开头的名字是男性,那么在文件male.txt中写下他的年龄,否则为male.txt 能帮到我吗

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

1 个答案:

答案 0 :(得分:0)

这是您要问的代码。

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)