[英]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.