2017-05-29 2 views

Répondre

1

Votre problème est que le nom de fichier est filepath en réalité, afin d'obtenir le nom du fichier, vous pouvez utiliser le module os

os.path.basename('filepath') 

donc pour écrire le fichier:

indexFile.write(os.path.basename(filename)+ ', ' + title.get_text(strip=True) + ', '+ ticker.get_text(strip=True) + ', ' + d_date.get_text(strip=True) + ', ' + parti_names + '\n') 
+0

comment puis-je l'appliquer à mon code? –

+0

J'ai ajouté comment l'utiliser –

+0

pour le nom de fichier dans glob.glob (os.path.join (chemin, '* .html')): print os.path.basename (filename) –

1

Vous pouvez utiliser:

path = 'C:/Users/.../.../output/' 
#read html files 
for filename in glob.glob(os.path.join(path, '*.html')): 
    soup = bs4.BeautifulSoup(open(filename).read(), "lxml") 
    title = soup.find('h1') 
    ticker = soup.find('p') 
    d_date = soup.find_all('div', {"id": "a-body"})[0].find_all("p")[2] 

    try: 
     def find_participant(tag): 
      return tag.name == 'p' and tag.find("strong", text=re.compile(r"Executives|Corporate Participants")) 

     participants = soup.find(find_participant) 
     parti_names = "" 
     for parti in participants.find_next_siblings("p"): 
      if parti.find("strong", text=re.compile(r"(Operator)")): 
       break 
      parti_names += parti.get_text(strip=True) + "," 
    except: 
     indexFile = open('C:/Users/.../output1/' + 'index.txt', 'a+') 
     indexFile.write(filename + ', ' + title.get_text(strip=True) + ', '+ ticker.get_text(strip=True) + ', ' + d_date.get_text(strip=True) + ', ' + 'No participants' + '\n') 
    else: 
     participants = soup.find(find_participant) 
     parti_names = "" 
     for parti in participants.find_next_siblings("p"): 
      if parti.find("strong", text=re.compile(r"(Operator)")): 
       break 
      parti_names += parti.get_text(strip=True) + "," 
     indexFile = open('C:/Users/.../output1/' + 'index.txt', 'a+') 
     indexFile.write(os.path.basename(filename) + ', ' + title.get_text(strip=True) + ', '+ ticker.get_text(strip=True) + ', ' + d_date.get_text(strip=True) + ', ' + parti_names + '\n') 
     indexFile.close() 
+0

Comment puis-je l'appliquer à mon code? –

+0

J'ai modifié mon message. J'espère que cela vous aide. –

0

ntpath est un autre mod ule utilisé pour obtenir le nom de base du chemin.

>>> import ntpath 
>>> ntpath.basename('C:/Users/.../output1/' + 'index.txt') 
'index.txt'