What I want to do:
- Extract sample1.tgz file.
- Store into 'sample1' directory
- Search a string from sample1/nvram2/log/TextFiles
Complete path => C:\Users\username\scripts\sample1\nvram2\logs\version.txt
Note: TextFiles are with different extensions
Example:
textFile.txt
textFile.txt.0
textFile.txt.1
textFile.log
textFile
What I have tried:
import os,tarfile, glob
string_to_search=input("Enter the string you want to search : ")
#all_files holds all the files in current directory
all_files = [f for f in os.listdir('.') if os.path.isfile(f)]
for current_file in all_files:
print("Reading " + current_file)
if (current_file.endswith(".tgz")) or (current_file.endswith("tar.gz")):
tar = tarfile.open(current_file, "r:gz")
#file_name contains only name by removing the extension
file_name=os.path.splitext(current_file)[0]
os.makedirs(file_name) #make directory with the file name
output_file_path=file_name #Path to store the files after extraction
tar.extractall(output_file_path) #extract the current file
tar.close()
#---Following code is to find the string from all the files in a directory---
path=output_file_path + '\nvram2\logs\*'
files=glob.glob(path)
for file1 in files:
with open(file1) as f2:
for line in f2:
if string_to_search in line:
#print file name which contains the string
print(file1)
#print the line which contains the string
print(str(line))
Issue:
I think, the problem is with path. It works, when I try to execute the code with the following code.
path='\nvram2\logs\*.txt'
But it checks only for '.txt' file extensions. But I want to search for all file extensions.
It does not work when I try the following code. Here output_file_path
contains sample1
i.e. the directory name
path=output_file_path + '\nvram2\logs\*'