List files in directory separately python - python

I'm working on a program that has a list of all files in a folder. Right now it only outputs the files as one entity, like one string. I need the files to each be displayed separately. Is there a way to do this?
This is the code I use:
import os
options = [
"Select a publisher",
os.listdir("C:/Users/bodig/Desktop/ad.olo exporter/config")
]
print(options)
The output:
['Select a publisher', ['bdu.json', 'ea.json', 'frz.json', 'fs.json', 'nfz.json', 'rht.json', 'taa.json', 'vol.json']]
The problem is that they are all one Entity. I can't figure out how to display them in a line. The output that I want is like this:
'Select a publisher'
'bdu.json'
'ea.json'
'frz.json'
'fs.json'
'nfz.json'
'rht.json'
'taa.json'
'vol.json'

options = ["Select a publisher"] + os.listdir("C:/Users/bodig/Desktop/ad.olo exporter/config")
for option in options:
print(option)

I don't exactly understand your problem, but with putting the file names out in separate lines I can help (as I think that is what you want). Just use a for loop:
print("Select a publisher:")
for i in os.listdir("C:/Users/bodig/Desktop/ad.olo exporter/config"):
print(i)
To print them all in one line, separated by commas, you could use:
print("Select a publisher:")
my_text = ""
for i in os.listdir("C:/Users/bodig/Desktop/ad.olo exporter/config"):
my_text += i + ", "
print(my_text)

you can modify your print statement, print like below.
import os
options = [
"Select a publisher",
os.listdir("C:/Users/bodig/Desktop/ad.olo exporter/config")
]
print(options[0], "\n", "\n".join(options[1])) # modified print
Output:
Select a publisher
bdu.json
ea.json
frz.json
fs.json
nfz.json
rht.json
taa.json
vol.json

Related

How to split text by comma into lines?

How to split a line of text by comma onto separate lines?
Code
text = "ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
fields = text.split(",")
text = "\n".join(fields)
Issue & Expected
But "\n" did not work. The result expected is that it adds new lines like:
ACCOUNTNUMBER=Accountnumber,
ACCOUNTSOURCE=Accountsource,
ADDRESS_1__C=Address_1__C,
ADDRESS_2__C
Note: I run it on Google Colab
if you want the commas to stay there you can use this code:
text = "ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
fields = text.split(",")
print(",\n".join(fields))
Your code should give this output
ACCOUNTNUMBER=Accountnumber
ACCOUNTSOURCE=Accountsource
ADDRESS_1__C=Address_1__C
ADDRESS_2__C
But if you want to seperate it by commas(,). You should add comma(,) with \n use text = ",\n".join(fields) instead of text = "\n".join(fields)
So the final code should be
text="ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
fields = text.split(",")
text = ",\n".join(fields)
print (text)
It will give your desirable output.
A more cross-compatible way could be to use os.linesep. It's my understanding that it's safer to do this for code that might be running on both Linux, Windows and other OSes:
import os
print("hello" + os.linesep + "fren")
I try to use print then it worked!, thank all you guys
You can use replace() :
text = "ACCOUNTNUMBER=Accountnumber,ACCOUNTSOURCE=Accountsource,ADDRESS_1__C=Address_1__C,ADDRESS_2__C"
print(text.replace(',',",\n"))
result:
ACCOUNTNUMBER=Accountnumber,
ACCOUNTSOURCE=Accountsource,
ADDRESS_1__C=Address_1__C,
ADDRESS_2__C

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

Need some help in deleting the data from list and again append it in same list

I have developed a Django app where user can upload multiple files. I can upload all the multiple files and its paths in the form of a list separated by comma(,) in MySql database.For example I have uploaded three files
Logging a Defect.docx,
2.Mocks (1).pptx and
3.Mocksv2.pptx
and it gets stored in database as following( Converting the individual file path into list and joining all the paths results in following form) :
FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx,
Now I need help while deleting particular file. For example when I'm deleting Logging a Defect.docx then I should be deleting first element of list alone and retain the other two paths. I'll be sending only name of document.
I'm retrieving the path as list and then I have to check if the name of doc being passed is there in each element of the list and if it matches then I should delete that element keeping the other elements intact. How to approach this ? It sounds like more of python question than Django question.
Use list-expression to filter the splitted text, and rebuild the string using join function
>>> db_path = 'FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx'
>>> file_to_delete = 'Logging a Defect.docx'
>>> file_separator = ","
>>> new_db_path = [
... path.strip()
... for path in db_path.split(file_separator)
... if path.strip() and file_to_delete not in path
... ]
>>> string_to_save = file_separator.join(new_db_path)
>>> string_to_save
'FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx'
You can read the text in your database and then use remove method of the list in python and then write back the new value into databse:
text = "FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx,"
splitted = text.split(',')
#filename is the one you want to delete
entry = "FileStore/client/{filename}".format(filename="Mocks (1).pptx")
if entry in splitted:
splitted.remove(entry)
newtext = ""
for s in splitted:
newtext += s
newtext += ','
now write back newtext to database
Not boasting or anything but I came up with my own logic for my question. It looks far less complicated but it works fine.
db_path = 'FileStore/client/Logging a Defect.docx,FileStore/client/Mocks (1).pptx,FileStore/client/Mocksv2.pptx'
path_list = db_path.split(",")
doc = 'Logging a Defect.docx'
for i in path_list :
if doc in i:
y.remove("FileStore/"+client+"/"+doc)
new_path = ",".join(y)
print new_path

Get all characters after a certain character?

Let's say I have a list of strings like this:
list1 = [
"filename1.txt",
"file2.py",
"fileexample.tiff"
]
How would I be able to grab all characters after the '.', if it's not too much to ask, by using "for i in" and have them come back in a list, like this: ['.txt','.py','.tiff']
If you are dealing with filepaths, then you should use the os.path module
import os.path
list1 = ["filename1.txt","file2.py","fileexample.tiff"]
print [os.path.splitext(f)[1] for f in list1]
prints
['.txt', '.py', '.tiff']
import os
for i in list1:
fileName, fileExtension = os.path.splitext(i)
print fileExtension
second one :
[i.split('.')[1] for i in list1]
map(lambda s:s.rsplit(".",1)[-1],my_list)
is probably how I would do it
which just splits from the right side exactly once on a period ... and gets whatever is on the right hand side for each item in the list

Printing list-of-lists in tabular form in Python

I have a list formatted like the following:
list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
I'd like to print out the contents of this list as a table with some headers. Here's what I've tried so far:
def dvdprintsoftlist():
print(list_of_DVDsoftwears)
''' printing the available DVDstocks,supplier's details '''
print("This is your current list of stock")
print("Supplier Name Softwear Name Amount")
print("----------------------------------------------------------------")
for (index,[name,softname,amount]) in enumerate (list_of_DVDsuppliers):
print(name + " " +softname + " " +str(amount) + " ")
print("----------------------------------------------------------------")
print("")
The problem is that this code doesn't align the table columns properly. How can I make sure all the entries are aligned with each other?
I'd also like to export my data in CSV format so that other programs can read it, but that's a separate question.
You could use format(), the {i:length} in string, will be replaced by the parameters, where i is an order identifier, and length is the "length" of the field.
def dvdprintsoftlist():
list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
print(list_of_DVDsuppliers)
print
''' printing the available DVDstocks,supplier's details '''
print("This is your current list of stock")
print("Supplier Name\t\tSoftwear Name\t\tAmount")
print("----------------------------------------------------------------")
for [name, softname, amount] in list_of_DVDsuppliers:
print("{0:23} {1:23} {2:5}".format(name, softname, amount))
print("----------------------------------------------------------------")
print("")
dvdprintsoftlist()
Try using the padding bits between the % and s while printing
you can use them like...
print('%-20s%-20s%-20s'%('supplier name','software name','amount'))
-for left padding and +ve(default) for right padding

Categories