To explore the pathogenesis and potential biomarkers of atrial fibrillation based on bioinformatics. Differentially expressed genes and module genes related to atrial fibrillation were obtained from GSE41177 and GSE79768 datasets (Chinese-origin tissue samples) through differential expression analysis and weighted gene co-expression network analysis. Candidate hub genes were obtained by taking intersections, and hub genes were obtained after gender stratification. Subsequently, functional enrichment analysis and immune infiltration analysis were performed. Four machine learning models were constructed based on the hub genes, and the optimal model was selected to construct a prediction nomogram. The prediction ability of the nomogram was verified using calibration curves and decision curves. Finally, potential therapeutic drugs for atrial fibrillation were screened from the DGIdb database. A total of 67 differentially expressed genes and 65 module genes related to atrial fibrillation were identified. Functional enrichment analysis indicated that the pathogenesis of atrial fibrillation was closely related to inflammatory response, immune response, and immune and infectious diseases. Four common hub genes (TYROBP, FCER1G, EVI2B and SOD2), and two genes specifically expressed in male (PILRA and SLC35G3) and female (HLA-DRA and GATP) patients with atrial fibrillation were obtained after gender-segregated screening. The extreme gradient boosting model had satisfactory diagnostic efficiency, and the nomogram constructed based on the hub genes, male significant variables (PILRA, SLC35G3 and SOD2), and female significant variables (FCER1G, SOD2 and TYROBP) had satisfactory predictive ability. Immune infiltration analysis demonstrated a disturbed immune infiltration microenvironment in atrial fibrillation with a higher abundance of plasma cells, neutrophils, and γδT cells, with a higher abundance of neutrophils in males and resting mast cells in females. Two potential drugs for the treatment of atrial fibrillation, valproic acid and methotrexate, were obtained by database and literature screening. The pathogenesis of atrial fibrillation is closely related to inflammation and immune response, and the microenvironment of immune cell infiltration of cardiomyocytes in the atrial tissue of patients with atrial fibrillation is disordered. TYROBP, FCER1G, EVI2B and SOD2 serve as potential diagnostic biomarkers of atrial fibrillation; PILRA and SLC35G3 serve as potential specific diagnostic biomarkers of atrial fibrillation in the male population, which can effectively predict the risk of atrial fibrillation development and are also potential targets for the treatment of atrial fibrillation.