It was during that investigation that the F.B.I. discovered on Mr. Weiner’s laptop a trove of emails belonging to his wife, Huma Abedin, a senior aide to Hillary Clinton. That led to an announcement in late October by James B. Comey, then the F.B.I. director, that the bureau had opened a new inquiry into Mrs. Clinton’s handling of official email. The inquiry ended two days before the election. Mrs. Clinton has blamed Mr. Comey in part for her defeat.

The judge, Denise L. Cote of Federal District Court in Manhattan, told Mr. Weiner that his offense was “a serious crime that deserves serious punishment.”

She said that there was a uniform opinion among those who had examined him that he had “a disease that involves sexual compulsivity; some call it a sex addiction.”

The judge said Mr. Weiner was finally receiving “effective treatment for this disease,” including attending group therapy and Sex Addicts Anonymous. “I find he is making an enormous contribution to others who are suffering from that same disease,” she added.

“But the difficulty here,” the judge said, “is that this is a very strong compulsion, so strong,” she continued, that “despite two very public disclosures and the destruction of his career on two occasions, he continued with the activity.”

She cited Mr. Weiner’s illegal exchanges with the girl on Skype, Snapchat and a site called Confide in early 2016. Prosecutors had said in their sentencing memo that during some of these communications, Mr. Weiner “used graphic and obscene language to ask the minor victim to display her naked body and touch herself, which she did.”

“The defendant knew this young woman was in high school and getting her learner’s permit,” Judge Cote said.