Taking file name from list and opening it? - python

I have list similar to this:
m=[['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']]
Now I want to these files
win=wave.open(m[0][3],'rb')
It is giving error how can I use this in this way...
I want to take the files name from the list
Please suggest???

do this:
m = [['qw','wew','23','C:/xyz/s.wav'],['qw','wew','23','C:/xyz/s2.wav'],['qw','wew','23','C:/xyz/s1.wav']]
fname = m[0][3]
print 'fname is', repr(fname)
win = wave.open(fname, 'rb')
and show us (using copy/paste into an edit of your question) everything that is printed, especially
(1) the result of print 'fname is', repr(fname)
(2) the ERROR MESSAGE

Related

Printing a Python List Vertically in Text File

This is probably a stupid question. I have scoured the forums here for a solution, but I cannot seem to implement it here within my code. I have attempted a .join method as well as + '\n' with absolutely no luck. If it goes well, nothing changes, and worse, it completely breaks. The code in question is below. The goal is to get the final print out in the text file to be vertical, not horizontal and jumbled together. Thank you all in advance. I also have similar code that I have successfully gotten to print out the way I wanted, but I cannot seem to replicate that here. Would be happy to provide if need be, but it is simply with print statements outside of the for loop, and the loop calls the loop variable to print. Pretty easy setup there.
import ipaddress
import random
import os
os.chdir('C:/Users/User/OneDrive/Desktop/')
network = ipaddress.ip_network('192.0.7.0/24')
network_list = list(network.hosts())
ip_network_list = []
with open ('IP Addresses.txt', 'r') as file:
ip_network_list = file.readlines()
ip_network_list = [x.strip() for x in ip_network_list]
variable = random.randint(1,20)
interesting_IPs = []
for x in range (0,variable):
randomly = random.randint(0,len(ip_network_list)-1)
ipaddr = ipaddress.ip_address(ip_network_list[randomly])
if ipaddr in network_list and ip_network_list[randomly] not in interesting_IPs:
network_list.remove(ipaddr)
ip_network_list.pop(randomly)
interesting_IPs.append(ipaddr)
with open ('Interesting IPs.txt', 'w') as file:
print ('The following are the interesting IPs:')
for x in range (len(interesting_IPs)):
print (interesting_IPs[x])
file.write(str(interesting_IPs[x]))
It's difficult to help you because without your input file (C:\Users\User\OneDrive\Desktop\IP Addresses.txt), we can't be sure your code is doing what's it's supposed to do.
But based on your code provided, here's my attempt:
import ipaddress
import random
import os
os.chdir('C:/Users/User/OneDrive/Desktop/')
network = ipaddress.ip_network('192.0.7.0/24')
network_list = set(network.hosts())
with open ('IP Addresses.txt') as input_file:
ip_network_list = {x.strip() for x in input_file}
sample_size = random.randint(1, min(20, len(ip_network_list)))
random_networks = {ipaddress.ip_address(x)
for x in random.sample(ip_network_list, sample_size)}
interesting_IPs = random_networks & network_list
with open ('Interesting IPs.txt', 'w') as output_file:
output_text = "\n".join(str(x) for x in interesting_IPs)
print ('The following are the interesting IPs:')
print(output_text)
output_file.write(output_text)
Is is near what you wanted to do?
It looks like you just want to print IPs to the file instead of just to the console. Use the file keyword argument of print.
with open ('Interesting IPs.txt', 'w') as file:
print ('The following are the interesting IPs:')
for ip in interesting_IPs:
print(ip)
print(str(ip), file=file)

Printing Python Output to .txt file

I'm having a bit of an issue trying to print the output of my code into a .txt file.
I am looking to print the results of my code to a .txt file, which I can then use the number printed as a variable for how many lines from the top of the .txt file to read from, separating that bit of text into it's own .txt file.
I have attached a link to a small diagram to explain this better 1
I've been researching for a while and can't seem to find it! Does anyone have any ideas on how to do this?
My code is the following:
from itertools import permutations
import string
# Enter new brand names to following lists
brand_names = "8x8, AmazonAWS, Checkpoint, Cisco, Citrix, Commvault, Dell, Dell_EMC, Google, Google_Cloud, HPE, Hyland, IBM, IBM_Cloud, Microsoft, Microsoft_Azure, NetApp, Oracle, Pure_Storage, SAP, Thompson_Reuters, Veritas, VMware, Aerohive, Aramark, Bloomberg, BMC, Box, CompuCom, Cybera, Extreme, FireEye, GE, Globoforce, GPSI, Infor, Lux_Research, MetTel, Oracle_Cloud, PAR_Invista, Puppet, Rackspace, Ruckus, Salesforce, SonicWall, SPI, Splunk, Stratix, Supermicro, Tenable, Ultipro, US_Bank, Veeam, VIP"
for group in permutations(['8x8', 'AmazonAWS', 'Checkpoint', 'Cisco', 'Citrix', 'Commvault', 'Dell', 'Dell_EMC', 'Google', 'Google_Cloud', 'HPE', 'Hyland', 'IBM', 'IBM_Cloud', 'Microsoft', 'Microsoft_Azure', 'NetApp', 'Oracle', 'Pure_Storage', 'SAP', 'Thompson_Reuters', 'Veritas', 'VMware', 'Aerohive', 'Aramark', 'Bloomberg', 'BMC', 'Box', 'CompuCom', 'Cybera', 'Extreme', 'FireEye', 'GE', 'Globoforce', 'GPSI', 'Infor', 'Lux Research', 'MetTel', 'Oracle_Cloud', 'PAR_Invista', 'Puppet', 'Rackspace', 'Ruckus', 'Salesforce', 'SonicWall', 'SPI', 'Splunk', 'Stratix', 'Supermicro', 'Tenable', 'Ultipro', 'US Bank', 'Veeam', 'VIP'], 3):
print('_'.join(group))
print
print
# Python3 code to demonstrate
# to count words in string
# using regex (findall())
import re
# printing original string
print ("The original string is : ")
print
print("'" + brand_names + "'")
# using regex (findall())
# to count words in string
res = len(re.findall(r'\w+', brand_names))
print
print
print
# printing result
print ("The number of brands are : " + str(res))
print
print
N = res
import sys
sys.stdout = open("file.txt", "w+")
print (group)
You'd use <filename>.write rather than print.
Using stdout would be dangerous and might affect parts of your code which you hadn't considered - I'd recommend removing that part of your code completely.
You can also use the > operator
python trial.py > trial.txt

Trying to write to multiple files with a single command with Python

EDIT I will try to clarify this question. I want to make two csv files. One with the text "Greetings", the other with the text "Greetings earth". The problem is I can't find a way to ask python to write to multiple files with one write command. I am trying to find a way to make things more efficient.
This question was identified as a possible duplicate of this. write multiple files at a time but there are a lot more parts to that question that I don't understand. I am trying to isolate this problem in as simple a question as I can.
hello = open("hello.csv","w")
world = open("world.csv","w")
everything = ['hello','world']
half = ['world']
everything.write("Greetings")
half.write("Earth")
hello.close()
world.close()
It is not entirely clear what any why you try to achieve.
If you need a function which manages 'all your file creation needs' you should probably approach this by creating the setup (file names -> contents) of your files then just write them. Alternatively you can label the files and generate their contents based on the preset 'flags'.
approach 1 is something like this:
file_dict = {'hello.csv': 'Greetings', 'world.csv': 'Greetings earth'}
for f in file_dict:
with open(f) as working:
working.write(file_dict[f])
approach 2 is something like this:
files = {'common': 'hello', 'custom': 'world'}
common_text = 'Greetings'
custom_text = ' earth'
for f in files.keys():
with open(files[f]+'.csv', 'w') as working_file:
text = common_text
if f is 'custom':
text += custom_text
working_file.write(text)
If you are happy with your implementation, you can migrate the 'writing' part to a separate function (something like this):
def write_my_stuffs():
for f in file_dict:
with open(f) as working:
working.write(file_dict[f])
file_dict = {'animal.csv': 'I like dogs',
'candy.csv': 'I like chocolate cake'}
write_my_stuffs()
csv","w")
world = open("world.csv","w")
everything = [hello,world]
half = [world]
for x in everything:
x.write("Greetings")
for x in half:
x.write(" Earth")
hello.close()
world.close()

How to pass string variable into search function?

I am having issues passing a string variable into a search function.
Here is what I'm trying to accomplish:
I have a file full of values and I want to check the file to make sure a specific matching line exists before I proceed. I want to ensure that the line <endSW=UNIQUE-DNS-NAME-HERE<> exists if a valid <begSW=UNIQUE-DNS-NAME-HERE<> exists and is reachable.
Everything works fine until I call if searchForString(searchString,fileLoc): which always returns false. If I assign the variable 'searchString' a direct value and pass it it works, so I know it must be something with the way I'm combining the strings, but I can't seem to figure out what I'm doing wrong.
If I examine the data that 'searchForString' is using I see what seems to be valid values:
values in fileLines list:
['<begSW=UNIQUE-DNS-NAME-HERE<>', ' <begPortType=UNIQUE-PORT-HERE<>', ' <portNumbers=80,443,22<>', ' <endPortType=UNIQUE-PORT-HERE<>', '<endSW=UNIQUE-DNS-NAME-HERE<>']
value of searchVar:
<endSW=UNIQUE-DNS-NAME-HERE<>
An example of the entry in the file is:
<begSW=UNIQUE-DNS-NAME-HERE<>
<begPortType=UNIQUE-PORT-HERE<>
<portNumbers=80,443,22<>
<endPortType=UNIQUE-PORT-HERE<>
<endSW=UNIQUE-DNS-NAME-HERE<>
Here is the code in question:
def searchForString(searchVar,readFile):
with open(readFile) as findMe:
fileLines = findMe.read().splitlines()
print fileLines
print searchVar
if searchVar in fileLines:
return True
return False
findMe.close()
fileLoc = '/dir/folder/file'
fileLoc.lstrip()
fileLoc.rstrip()
with open(fileLoc,'r') as switchFile:
for line in switchFile:
#declare all the vars we need
lineDelimiter = '#'
endLine = '<>\n'
begSWLine= '<begSW='
endSWLine = '<endSW='
begPortType = '<begPortType='
endPortType = '<endPortType='
portNumList = '<portNumbers='
#skip over commented lines -(REMOVE THIS)
if line.startswith(lineDelimiter):
pass
#checks the file for a valid switch name
#checks to see if the host is up and reachable
#checks to see if there is a file input is valid
if line.startswith(begSWLine):
#extract switch name from file
switchName = line[7:-3]
#check to make sure switch is up
if pingCheck(switchName):
print 'Ping success. Host is reachable.'
searchString = endSWLine+switchName+'<>'
**#THIS PART IS SUCKING, WORKS WITH DIRECT STRING PASS
#WONT WORK WITH A VARIABLE**
if searchForString(searchString,fileLoc):
print 'found!'
else:
print 'not found'
Any advice or guidance would be extremely helpful.
Hard to tell without the file's contents, but I would try
switchName = line[7:-2]
So that would look like
>>> '<begSW=UNIQUE-DNS-NAME-HERE<>'[7:-2]
'UNIQUE-DNS-NAME-HERE'
Additionally, you could look into regex searches to make your cleanup more versatile.
import re
# re.findall(search_expression, string_to_search)
>>> re.findall('\=(.+)(?:\<)', '<begSW=UNIQUE-DNS-NAME-HERE<>')[0]
'UNIQUE-DNS-NAME-HERE'
>>> e.findall('\=(.+)(?:\<)', ' <portNumbers=80,443,22<>')[0]
'80,443,22'
I found how to recursively iterate over XML tags in Python using ElementTree? and used the methods detailed to parse an XML file instead of using a TXT file.

New to python struggling with append

Hey I've looked around but can't seem to find an answer. I am looking to identify and print the number of files in a list & their names, but keeping running into a an error. I am new to python so I am quite sure I got something wrong and apologize if this is a stupid question. Below is the code I have so far
import os
folderpath = "C:\Users\Michaelf\Desktop\GEOG M173\LabData"
filelist = os.listdir(folderpath)
print filelist
Counter_Shapefiles = 0
Names_of_Shapefiles = 0
for the_file_name in filelist:
File_Extension = the_file_name[-4:]
if "file_Extension == .shp":
Counter_Shapefiles= Counter_Shapefiles + 1
Names_of_Shapefiles.append
to use append you need a list not an int so
Name_of_Shapefiles = 0
should be
Name_of_Shapefiles = []
Second, the syntax for append is Names_of_Shapefiles.append(the_file_name)
Names_of_Shapefiles is an int. change that to a list and add what you want appended into the append call.
Also, when adding questions, note what errors you get for future reference.
import os
folderpath = "C:\Users\Michaelf\Desktop\GEOG M173\LabData"
filelist = os.listdir(folderpath)
print filelist
Counter_Shapefiles = 0
Name_of_Shapefiles = []
for the_file_name in filelist:
File_Extension = the_file_name[-4:]
if File_Extension == ".shp":
Counter_Shapefiles = Counter_Shapefiles+1
Names_of_Shapefiles.append(the_file_name)
Have a look at the changes that I've made to your code.
For if statements you don't want your condition to be in quotation marks, as that turns it into a string. If you want to make it clear that it's your statement then you can use brackets, but it's not necessary
In that same if statement you type file_Extension without a capital f, which isn't the same as File_Extension, so your if statement doesn't know what it's looking for.
For your ".shp" string, that does need to be in quotation marks, to make it clear that it's a string.
When defining your Names_of_Shapefiles array, you need to put it in square brackets, or it'll automatically become a number instead of an array.
The .append is a function, and takes input; how else would your program know what to append to the Names_of_Shapefiles array? This is why you put what you want appending inside the brackets at the end.

Categories