I am new to python. I have a few text files in a directory, and a seperate textfile maintained the original links for each of the text files. Ie, I have 1.txt,2.txt and 3.txt saved in the directory, and I have weblink text file(line 1(wiki.com/a) is the link for 1.txt, line 2(wiki.com/b is the link for 2.txt...). I am able to get the text file names, but I can't use the result to find the links from the weblink text file.
#first part
path = 'C:\\Users\\PycharmProjects\\pythonProject1\\Document'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print(files) #result from here is ['1', '2', '3']
#second part
file = open("C:\\Users\\PycharmProjects\\pythonProject1\\link.txt")
specified_lines = files #files are taking the result from first part
for pos, l_num in enumerate(file):
if pos in specified_lines:
print(l_num)
if i use specified_lines = [0,1,2] then the function works, how do i incorporate the output from my first part into my second part? As of right now, specified_lines = files in the second part return nothing.
CodePudding user response:
Hope this helps.
- Try printing
pos
, I see its 0 based so you may want to offsetpos
- Try converting the
pos
from integer to string before searching
import os
path = '.'
files = [os.path.splitext(filename)[0] for filename in os.listdir(path)]
print(files) #result from here is ['1', '2', '3']
#second part
file = open("weblink")
specified_lines = files #files are taking the result from first part
for pos, l_num in enumerate(file):
print(pos)
if str(pos 1) in specified_lines:
print(l_num)
Output from my try:
['orig', 'weblink', 'notes', '3', '2', '1']
0
wiki.com/a
1
wiki.com/b
2
wiki.com/c