繁体   English   中英

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

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

我想逐行读取文件,首先对第一个值执行一些操作,然后再次从文件中读取第二个值,想要执行一些操作,例如,如果我有一个文件,其值是Vik John Lisa

我想一一阅读并传递到sql server,然后根据性别在文件中写入输出(年龄)。如果以Vik开头的名字是男性,则在文件male.txt中输入他的年龄,否则在female.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

这是您要的代码。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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