Open all files in different directory python -


i need open file different directory without using it's path while staying in current directory.

when execute below code:

for file in os.listdir(sub_dir):     f = open(file, "r")     lines = f.readlines()     line in lines:         line.replace("dst=", ", ")         line.replace("proto=", ", ")         line.replace("dpt=", ", ") 

i error message filenotfounderror: [errno 2] no such file or directory: because it's in sub directory.

question: there os command can use locate , open file in sub_dir?

thanks! -let me know if repeat, searched , couldn't find 1 may have missed it.

os.listdir() lists only filename without path. prepend these sub_dir again:

for filename in os.listdir(sub_dir):     f = open(os.path.join(sub_dir, filename), "r") 

if doing loop on lines file, loop on file itself; using with makes sure file closed when done too. last not least, str.replace() returns new string value, not change value itself, need store return value:

for filename in os.listdir(sub_dir):     open(os.path.join(sub_dir, filename), "r") f:         line in f:             line = line.replace("dst=", ", ")             line = line.replace("proto=", ", ")             line = line.replace("dpt=", ", ") 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -