简体   繁体   中英

Python checking data in file

I am attempting to figure out the python code for a specific process. If any of the lines in file1 are not in file2 I want to append the contents of file2 to file3. I attempted a nested for loop and am just writing test data to make sure the iterations are working properly. I am only receiving the same number of lines as int text2.txt and I expected it to have responses the number of line in text2 times the number of lines in text1.

file1=open(text1.txt, 'r+')
file2=open(text2.txt, 'r+')
file3=open(text3.txt, 'a+')
for line1 in file1:
   for line2 in file2:
     if line1==line2:
      file3.write("same" + '\r\n')
     else:
      file3.write("different" + '\r\n')

Example

file1
Tom
Harry

file2
Harry
Tom
Lilly

Print nothing in file3.

File1 is the same as above
File2
Harry
Lilly
David

File3 should read *I understand my code doesn't read this way today.
Harry
Lilly
David

File3 reads today
different
different
different

File3 what I expected
different
different
different
same
different
different

Please explain how I get to my ultimate goal and what did I do wrong?

Either read two file content into two list and use in operator to check if element in one list is in another list. also open file3 in write mode, append mode will append to what previously it had.

file1=open(text1.txt, 'r+') file2=open(text2.txt, 'r+') file3=open(text3.txt, 'a+') for line1 in file1: if line1 in file2: file3.write("same" + '\\r\\n') else: file3.write("different" + '\\r\\n')

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