I'm starting a python script to parse a number of small text files in a folder. I need to retrieve particular information that will always be different (in this case hostname, model & serial number for a Cisco switch) and so can't use a regular expression. However I can easily find the line that contains the information. This is what I have so far:
import os
def parse_files(path):
for filename in os.listdir(path):
with open(filename,'r').read() as showfile:
for line in showfile:
if '#sh' in line:
hostname = line.split('#')[0]
if 'Model Number' in line:
model = line.split()[-1]
if 'System serial number' in line:
serial = line.split()[-1]
showfile.close()
path = raw_input("Please specify Show Files directory: ")
parse_files(path)
print hostname,model,serial
This, however, is returning:
Traceback (most recent call last):
File "inventory.py", line 17, in <module>
parse_files(path)
File "inventory.py", line 5, in parse_files
with open(filename,'r').read() as showfile:
IOError: [Errno 2] No such file or directory: 'Switch01-run.txt'
where 'Switch01-run.txt' is a file in the specified folder. I can't figure out where I'm taking a wrong turn.
The problem is that os.listdir() is returning the filenames from the directory, not the complete path to the file.
You need to do this instead:
with open(os.path.join(path,filename),'r') as showfile:
This fixes two issues - the IOerror, and the error you will get trying to read lines from a string.
Related
I know there are questions like that but I still wanted to ask this because I couldn't solve, so there is my code:
#! python3
import os
my_path = 'E:\\Movies'
for folder in os.listdir(my_path):
size = os.path.getsize(folder)
print(f'size of the {folder} is: {size} ')
And I got this error:
Traceback (most recent call last):
File "c:/Users/ataba/OneDrive/Masaüstü/Programming/python/findingfiles.py", line 7, in <module>
size = os.path.getsize(folder)
File "C:\Program Files\Python37\lib\genericpath.py", line 50, in getsize
return os.stat(filename).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'FordvFerrari1080p'
When I write print(folder) instead of getting their size it shows the folders so I don't think the program can't find them.
The problem may be that you are passing as an argument to os.path.getsize() just the folder name instead of the whole path to the folder
It may be that you have the file name as 'FordvFerrari1080p' rather than 'FordvFerrari1080p.mp4' (or whatever file type it may be)
I am trying to open a txt file for reading with this code:-
type_comments = [] #Declare an empty list
with open ('society6comments.txt', 'rt') as in_file: #Open file for reading of text data.
for line in in_file: #For each line of text store in a string variable named "line", and
type_comments.append(line.rstrip('\n')) #add that line to our list of lines.
Error:-
Error - Traceback (most recent call last):
File "c:/Users/sultan/python/society6/society6_promotion.py", line 6, in <module>
with open ('society6comments.txt', 'rt') as in_file:
FileNotFoundError: [Errno 2] No such file or directory: 'society6comments.txt'
I already have a file name with 'society6comments.txt' in the same directory has my script so why is it showing error?
The fact that the text file is in the same directory as your program does not make that directory the current working directory. Put the full path to the file in your open() call.
You can use os.path.dirname(__file__) to obtain the directory name of the script, and then join the file name you want:
import os
with open (os.path.join(os.path.dirname(os.path.abspath(__file__)), 'society6comments.txt'), 'rt') as in_file:
I'm trying to read this .txt file through Python (3.6.5), using SublimeText3 (3.1.1). learning_python.txt is in the same directory as my python program. I tried to make it an absolute filepath but getting FileNotFoundError either way. I also tried running it through Terminal with the same outcome. Is the code wrong?
filename = 'learning_python.txt'
print("--- Reading in the entire file:")
with open(filename) as f:
contents = f.read()
print(contents)
Traceback is:
--- Reading in the entire file:
Traceback (most recent call last):
File "C:\Users\sulli\Documents\Coding\Python Crash Course\Ch_10_Files_Exceptions\about_python.py", line 6, in <module>
with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/sulli/Documents/Coding/Python Crash Course/Ch_10_Files_Exceptions/learning_python.txt'
Looks like the issue here was I had named learning_python.txt file with the .txt at the end just like it is in the code. When I deleted the .txt on the text file itself, it worked in Python to find learning_python.txt. Python must have seen it as learning_python.txt.txt.
I am trying to loop over a Python directory, and I have a specific file that happens to be the last file in the directory such that I get an IOerror for that specific file.
The error I get is:
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My script:
for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
data.append(k_fold(filename))
continue
else:
continue
k_fold does this:
def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()
The entire traceback:
Traceback (most recent call last):
File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My CSV files are such:
nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv
...
nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv
Why doesn't it recognize my nod_gyro_instance_10_P_4.csv file?
os.listdir returns just filenames, not absolute paths. If you're not currently in that same directory, trying to read the file will fail.
You need to join the dirname onto the filename returned:
data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
k_fold(os.path.join(data_dir, filename))
Alternatively, you could use glob to do both the listing (with full paths) and extension filtering:
import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
k_fold(filename)
I can't quite make the leap despite pre-existing similar questions. Help would be valued!
I am trying to recursively parse all xml files in the directory/sub directory
I am looking for the value that appears for the tag "Operator id"
Example source XML:
<Operators>
<Operator id="OId_LD">
<OperatorCode>LD</OperatorCode>
<OperatorShortName>ARRIVA THE SHIRES LIMIT</OperatorShortName>
This is the code I have thus far:
from xml.dom.minidom import parse
import os
def jarv(target_folder):
for root,dirs,files in os.walk(target_folder):
for targetfile in files:
if targetfile.endswith(".xml"):
print targetfile
dom=parse(targetfile)
name = dom.getElementsByTagName('Operator_id')
print name[0].firstChild.nodeValue
This is the terminal command I am running:
python -c "execfile('xml_tag.py'); jarv('/Users/admin/Projects/AtoB_GTFS')"
And this is the error I receive:
tfl_64-31_-37434-y05.xml
encodings.xml
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "xml_tag.py", line 8, in jarv
dom=parse(targetfile)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/minidom.py", line 1918, in parse
return expatbuilder.parse(file)
File "/usr/local/Cellar/python/2.7.8_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/dom/expatbuilder.py", line 922, in parse
fp = open(file, 'rb')
IOError: [Errno 2] No such file or directory: 'encodings.xml'
(frigo)andytmac:AtoB_GTFS admin$ python -c "execfile('xml_tag.py'); jarv('/Users/admin/Projects/AtoB_GTFS')"
tfl_64-31_-37434-y05.xml
If I comment out the code after the 'print target file' line it does list all the xml files I have.
Thanks for your assistance,
Andy
You're not looking at the right place (relative path) : when you use for root, dirs, files in os.walk(target_folder):, files is a list of the file names in the directory root, and not their absolute path.
Try remplacing dom=parse(targetfile) by dom = parse(os.sep.join(root, targetfile))