I have two lists where I have the same number of files. The files in both folders have the same names, for example:
JavaScript
x
5
1
Test1 folder:
2
files.txt
3
test.txt
4
name.txt
5
and so on. In the test2 folder I have the same named files. How can I compare for each file if the data in both files is the same? So whether:
JavaScript
1
4
1
test1 / files.txt = test2 / files.txt
2
test1 / test.txt = test2 / test.txt
3
test1 / name.txt = test2 / name.txt
4
JavaScript
1
20
20
1
import os
2
import difflib
3
4
test1_path = "C:/Users/admin/Desktop/test1"
5
test2_path = "C:/Users/admin/Desktop/test2"
6
7
if os.path.exists(test1_path):
8
files_test1 = []
9
for name in os.listdir(test1_path):
10
if os.path.isfile(os.path.join(test1_path, name)):
11
files_test1.append(os.path.join(test1_path, name))
12
13
if os.path.exists(test2_path):
14
files_test2 = []
15
for name in os.listdir(test2_path):
16
if os.path.isfile(os.path.join(test2_path, name)):
17
files_test2.append(os.path.join(test2_path, name))
18
19
20
Are you able to advise something?
Advertisement
Answer
You don’t need to perform two loops. One is enough. Also you can use the filecmp
package to compare file contents.
JavaScript
1
19
19
1
import os
2
import filecmp # to compare files
3
4
test1_path = 'C:/Users/admin/Desktop/test1'
5
test2_path = 'C:/Users/admin/Desktop/test2'
6
7
if os.path.exists(test1_path) and os.path.exists(test2_path):
8
all_same = True
9
for name in os.listdir(test1_path):
10
file1 = os.path.join(test1_path, name)
11
file2 = os.path.join(test2_path, name)
12
if (
13
os.path.isfile(file1) and
14
os.path.isfile(file2) and
15
not filecmp.cmp(file1, file2)
16
):
17
all_same = False
18
print('all files are the same:', all_same)
19
Note that the code can be simplified if you know for sure that both directories contain the same file names.