To achieve this, you can read the contents of both files and then compare the usernames from file1.txt
with the user details in file2.txt
. Here’s a simple way to do it in Python:
python# Read usernames from file1.txt
with open('file1.txt', 'r') as file1:
usernames = file1.read().splitlines()
# Read user details from file2.txt
with open('file2.txt', 'r') as file2:
user_details = file2.read().splitlines()
# Create a dictionary to store user details
user_dict = {}
for line in user_details:
parts = line.split()
username = parts[0]
if username in usernames:
user_dict[username] = ' '.join(parts[1:])
# Print the shortlist of user details
for username, details in user_dict.items():
print(f'{username} {details}')
This code reads the usernames from file1.txt
into a list and the user details from file2.txt
into another list. It then iterates over the user details, extracts the username, and checks if it’s in the list of usernames from file1.txt
. If it is, it adds the user details to a dictionary. Finally, it prints the shortlist of user details.
المزيد من المعلومات
للقيام بذلك، يمكنك استخدام مكتبة pandas
في Python لتحميل بيانات المستخدمين من الملفين ومن ثم دمج البيانات استنادًا إلى اسم المستخدم. إليك كيفية القيام بذلك:
pythonimport pandas as pd
# Load usernames from file1.txt
usernames_df = pd.read_csv('file1.txt', header=None, names=['username'])
# Load user details from file2.txt
user_details_df = pd.read_csv('file2.txt', header=None, names=['username', 'date', 'time', 'code'])
# Merge the dataframes on the 'username' column
merged_df = pd.merge(usernames_df, user_details_df, on='username', how='inner')
# Print the shortlist of user details
print(merged_df)
هذا الكود يستخدم pandas
لتحميل بيانات المستخدمين من الملفين file1.txt
و file2.txt
إلى إطار بيانات (dataframe)، ثم يدمج الإطارين بناءً على عمود اسم المستخدم. النتيجة ستكون إطار بيانات يحتوي على البيانات المطلوبة، يمكنك طباعته للحصول على النتائج المطلوبة.