Can you let me know how to print the values based upon the key pair.
cat output.txt
tamil nadu US_input1.csv
andra US_input1.csv
kar nata kaka US_input1.csv
madhya pradesh US_input2.csv
goa US_input2.csv
new delhi city US_input2.csv
jaipur city express US_input3.csv
email_file='output.txt'
for line in TEXT_LIST:
TEXT=TEXT+"\n"+line
Output :
tamil nadu US_input1.csv
andra US_input1.csv
kar nata kaka US_input1.csv
madhya pradesh US_input2.csv
goa US_input2.csv
new delhi city US_input2.csv
jaipur city express US_input3.csv
Expected output :
US_input1.csv
tamil nadu
andra
kar nata kaka
US_input2.csv
madhya pradesh
goa
new delhi city
US_input3.csv
jaipur city express
I would have thought that a dictionary object would be the tool to use. To do that, you’ll need to build a dictionary, from your data, but your data will need a delimiter, such as a comma, then you can use the csv library for the file read.
The dictionary would look something like this:
data = {
'US_input1.csv': ['tamil nadu', 'andra', 'kar nata kaka']
}
… from which you could extract the data and display it like this:
for key in data:
print(key)
print('\n'.join(data[key]))
"""
Output:
US_input1.csv
tamil nadu
andra
kar nata kaka
"""
Yeah i can add a demiliter , in the output.txt file.
can you let me know to pass the output.txt to the data dictionary variable.
Output.txt is a normal text file.
Output :
tamil nadu,US_input1.csv
andra,US_input1.csv
kar nata kaka,US_input1.csv
madhya pradesh,US_input2.csv
goa,US_input2.csv
new delhi city,US_input2.csv
jaipur city express,US_input3.csv
import csv
data = {}
with open('output.txt', 'r') as file:
reader = csv.reader(file)
for row in reader:
name = row[0]
key = row[1]
if key in data:
data[key].append(name)
else:
data[key] = [name]
for key in data:
print(key)
print('\n'.join(data[key]))
"""
Output:
US_input1.csv
tamil nadu
andra
kar nata kaka
US_input2.csv
madhya pradesh
goa
new delhi city
US_input3.csv
jaipur city express
"""
For me, I’d change the upstream filename to output.csv.
I’ve never even tried to code anything to do with email in Python and as such, I’m not in any position to be able to advise on that.
That said, I’ll have look at your code and see if I can help.
To add: you seem to have a few different threads here that all seem to be related, which I think is a little confusing, both you as well as those that are trying to help. I think you need to evaluate what you have, try and code this up and post back (maybe in a new thread) with what you are still not able to do.
temp_file = "temp.txt"
with open(temp_file, mode='w', encoding='UTF-8') as temp:
# mode='w' will create a new file or overwrite the contents of an existing file.
# Use mode='a' to Write data to the end of an existing file.
for key in data:
print(key, file=temp)
print('\n'.join(data[key]), file=temp)