Print output to separate text files - python-3.x

The script below opens devices.csv and reads the rows, then prints 2 of the fields. I want to create a separate .txt file for each row using 'Host Name' field, then print 'Configuration Text' to each file.
import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
reader = csv.DictReader(infile)
for row in reader:
print(row['Host Name'], row['Configuration Text'])
Please assist.

import csv
import sys
import os
path = 'C:/configs'
fh = "C:/configs/devices.csv"
with open(fh, mode='r') as infile:
reader = csv.DictReader(infile)
for row in reader:
with open(os.path.join(path, row['Host Name']), "w") as outfile: #Create File with host name
outfile.write(row['Configuration Text']) #Write Content

Related

Dynamically create file folder based on line 1 in csv

This script downloads images, renames them based on line[0] adds a number to the end of the file name and saves them to a file folder. My goal here is to create the file folder name based on line[0] of my csv file, I'm new to python and need to download/sort 15000+ images. Any help would be appreciated! Using python 3.8.6
Note: 1 model may contain many images so the idea is to create the folder, place images for that model inside, move on to the next model, etc.
Csv file content
RHV3-484-L,https://www.fisherpaykel.com/on/demandware.static/-/Sites-fpa-master-catalog/default/dw0c85e188/product-mugs/cooking/ranges/mug/retail/RHV3-484-N-RHV3-484-L-external-mug-rs-84.png
RHV3-484-L,https://www.fisherpaykel.com/on/demandware.static/-/Sites-fpa-master-catalog/default/dwcbd711e5/inspire/caitlin-wilson-portland-dk-339-rs-84.png
RHV3-484-L,https://www.fisherpaykel.com/on/demandware.static/-/Sites-fpa-master-catalog/default/dw3702e52a/inspire/caitlin-wilson-portland-dk-385-rs-84.jpg
RHV3-484-L,https://www.fisherpaykel.com/on/demandware.static/-/Sites-fpa-master-catalog/default/dw0c85e188/product-mugs/cooking/ranges/mug/retail/RHV3-484-N-RHV3-484-L-external-mug-rs-84.png
RHV3-484-L,https://www.fisherpaykel.com/on/demandware.static/-/Sites-fpa-master-catalog/default/dwf99a5a9d/inspire/david-berridge-project-brooklyn-mw-6457-rs-84.jpg
Python script
import sys
import urllib
import urllib.request
from csv import reader
import os.path
import os
csv_filename = "images"
with open(csv_filename+".csv".format(csv_filename), 'r') as csv_file:
n = 1
for line in reader(csv_file):
if not os.path.exists("ImageID"):
os.makedirs("ImageID")
print("Image skipped for {0}".format(line[0]))
else:
if line[1] != '' and line[0] != "ImageID":
urllib.request.urlretrieve(line[1], "ImageID/" + line[0] + "-" + str(n) + ".jpg")
n += 1
print("Image saved for {0}".format(line[0]))
else:
print("No result for {0}".format(line[0]))
This seems to work as desired....
Couple comments in middle. Notably, you need to respect the .jpg or .png file. If you have file extensions that are longer (4 chars) you may need to split out the file name and then split by "."
Good Luck!
import sys
import urllib
import urllib.request
from csv import reader
import os.path
import os
csv_filename = "images.csv"
with open(csv_filename, 'r') as csv_file:
n = 1 # starting point
for line in reader(csv_file):
tgt_folder = line[0]
if not os.path.exists(tgt_folder):
os.makedirs(tgt_folder)
n = 1 # restart n if you find a NEW folder
# there should be no "else" clause here. Just test the folder name above, but don't waste a file
if line[1] != '' and line[0] != "ImageID": # not clear what this is for... ??
filename = ''.join([line[0], '-', str(n), line[1][-4:]])
destination = os.path.join(tgt_folder, filename)
urllib.request.urlretrieve(line[1], destination)
n += 1
print("Image saved for {0}".format(line[1]))
else:
print("No result for {0}".format(line[1]))

Merge two names /or just extract names from CSV file

I want to read csv file containing different names and merge two names into one.
for example:
google.com , facebook.com
should generate something like
googleface.com or googlebook.com
import csv
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize
ps = PorterStemmer()
with open('C:/Users/upadh/Desktop/domains.txt', 'r') as csvFile:
csvReader = csv.DictReader(csvFile, delimiter=',')
string ={}
count =0
for row in csvReader:
# for row in csvReader:
#if row is 0 :
for header, value in row.items():
try:
string[header].append(value)
except KeyError:
string[header] = [value]
for w in sorted(str(string)):
print(w, " : ", ps.stem(w))
Extract names can be done like this:
import csv
with open('inputCSV.txt', 'r') as csvFile:
csvReader = csv.reader(csvFile, delimiter=',')
for line in csvReader:
#prints all 'names' in the csv file, here you can add code to do whatever.
[print(name) for name in line]

How to convert multiple CSV files in directory to pipe-delimited text files using Python3

So I'm new to Python(3) and need to create a loop that will go through almost 200 CSV files and convert them each into a pipe-delimited .txt file (with the same name).
I have code that does this for 1 file and works perfectly:
import csv
with open('C:/Path/InputFile.csv', 'r') as fin, \
open('C:/Path/OutputFile.txt', 'w') as fout:
reader = csv.DictReader(fin)
writer = csv.DictWriter(fout, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)
Thanks in advance.
You would modify your code to:
for in_name, out_name in zip(list_of_in_names, list_of_out_names):
with open(in_name, 'r') as fin, open(out_name, 'w') as fout:
...
Where list_of_in_names and list_of_out_names names of files you want to read from and write to respectively.
Edit: To address the issue from the comments you can use the pathlib library:
from pathlib import Path
for in_path in Path('C:/Path').glob('*.csv'):
out_path = in_path.with_suffix('.txt')
with in_path.open('r') as fin, out_path.open('w') as fout:
...

Rename a file/ remove numbers from a file name in python 3

My code runs well when I didn't ask to rename the file, just to print all file names without number, but when I did it and checked file instead of running it, it just doesn't work.
here's my code:
import os
import re
def rename_file():
file_list = os.listdir(r"C:\Users\Zoe.Zhao\Desktop\prank")
saved_path = os.getcwd()
os.chdir(r"C:\Users\Zoe.Zhao\Desktop\prank")
print (saved_path)
for file_name in file_list:
file_name = re.sub('[0-9]','',file_name)
print(file_name)
rename_file()
Here are some sreenshots:
before:
after:
You need to create a new list: see below:
import os
import re
def rename_file():
file_list = os.listdir(r"C:\Users\afareh\Dropbox\PROGRAMMING\test\prank\prank")
saved_path = os.getcwd()
os.chdir(r"C:\Users\afareh\Dropbox\PROGRAMMING\test\prank\prank")
new_file_list=[] # create an empty list for storing the names of the renamed files.
for file_name in file_list:
file_name=re.sub('[0-9]','',file_name)
new_file_list.append(file_name)
print (new_file_list)
rename_file()

Writing to csv file more than one user input?

I have a user input. The first is for user to put in their name. The following will be destinations.
The below code writes to line 1 in csv. Hover if the code runs again and user inputs a different name I want it to write to the next line. Line 2.
class writeToCSVfile:
def __init__(self):
self.name = []
def writeIt(self):
import csv
with open('test.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
data = [['Name', 'Home Airport','Destination' 'Stopovers','Cheapest Route'],
[b.name, xy, b.input2, b.input3 ],
a.writerows(data)
writ = writeToCSVfile()
writ.writeIt()
What the CSV file looks like now
Just use append mode when openinig the file and should work:
with open('test.csv', 'a', newline='') as fp:
You must deal with the headers
['Name', 'Home Airport','Destination' 'Stopovers','Cheapest Route']
to not append them everytime to the file.

Resources