Finding the right commands to output the correct csv contents [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
When I output it, it should be coming out as this:
{'d': '400', 'e': '500', 'f': '600'}
{'celery': '2.81', 'milk': '4.34', 'bread': '5.63'}
but instead, it comes out as this:
{'d': ' 400', ' e': ' 500', ' f': ' 600'}
{'celery': ' 2.81', ' milk': ' 4.34', ' bread': ' 5.63'}
Here's my code:
import csv
f_name = input()
dictionary1 = {}
dictionary2 = {}
f = open(f_name, 'r')
context = csv.reader(f)
data = []
for row in context:
data.append(row)
for i in range(0, len(data[0]), 2):
dictionary1[data[0][i]] = data[0][i+1]
for i in range(0, len(data[1]), 2):
dictionary2[data[1][i]] = data[1][i+1]
print(dictionary1)
print(dictionary2)
f.close()

Related

how to print the exception from exce? My code is in string. It works fine on the correct code snippet. not on error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
This post was edited and submitted for review 4 days ago and failed to reopen the post:
Not suitable for this site
Improve this question
import os
path = "C:\\Users\\Abdul Rafay\\Downloads\\Compressed\\day3_t1\\day3_t1"
file_name = os.listdir(path)
word1 = "email"
word2 = "return"
word3 = "def"
x = ""
y = "5"
for i in file_name:
path1 = os.path.join(path, I)
with open(path1, 'r') as fp:
lines = fp.readlines()
for line in lines:
if line.find(word1) != -1:
print("File: ",path1)
print("Email: ",line.strip("email= "))
elif line.find(word2) != -1 or line.find(word3) != -1:
x += line
if 'def' in x and 'return' in x:
print("Solution(5): ")
exec(x + """
try:
print(solution("""+str(y)+"""))
except Exception as err:
print(err)
""")
print("=========================")
x = ""
#The End---------------------------------------The End
Type 1 (with Error)
Type 2 (No Error)
I am reading the "solution" method from these files. and pass the parameter using exec and execute the function.
But the problem is when there is no error in the code it works fine but if there is a error it doesn't show the exception.
This is the output. when there is error it prints the particular function multiple times.

Have some issues with python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 days ago.
Improve this question
im using this phone number validator but since they changed the api url its not working anymore..
Here is the original code:
phone_number = open(input(f'\n{cy}Enter Phone Number List{res} : '),'r').read().splitlines()
access_key = input(f'\n{yl}Enter Your Access Key {red}[ Numverify ]{res} : ')
print('------------------------------------------------------------------')
for i in phone_number :
url = 'http://apilayer.net/api/validate?access_key=' + access_key + '&number=' + str(i)
response = requests.get(url)
answer = response.json()
if answer["carrier"] :
print(f'{gr}{answer["number"]}{res}{yl} => {cy}{answer["carrier"]}{res}')
save = open(f'Result/{answer["carrier"]}.txt', 'a+')
save.write(str(i) + '\n')
else:
print(f'{red}{answer["number"]} => Die{res}')
dk = open('Result/die.txt', 'a+')
dk.write(str(i) + '\n')
Previously, the API endpoint to perform a numverify scan was as follows.
GET https://apilayer.net/api/validate?access_key=access_key&number=phone_number
This has been changed to the following.
GET https://api.apilayer.com/number_verification/validate?number=phone_number
apikey: access_key
how to fix this?
Update the URL in the code as follows:
phone_number = open(input(f'\n{cy}Enter Phone Number List{res} : '),'r').read().splitlines()
access_key = input(f'\n{yl}Enter Your Access Key {red}[ Numverify ]{res} : ')
print('------------------------------------------------------------------')
headers = {'apikey': access_key}
for i in phone_number :
url = 'https://api.apilayer.com/number_verification/validate?number=' + str(i)
response = requests.get(url, headers=headers)
answer = response.json()
if answer["carrier"] :
print(f'{gr}{answer["number"]}{res}{yl} => {cy}{answer["carrier"]}{res}')
save = open(f'Result/{answer["carrier"]}.txt', 'a+')
save.write(str(i) + '\n')
else:
print(f'{red}{answer["number"]} => Die{res}')
dk = open('Result/die.txt', 'a+')
dk.write(str(i) + '\n')

Create files in a specific directory [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to create a file (.txt) in the data directory but it creates a folder
This is the code I am using
How can I create the file
lenID = abs(len(id) - 5)
nameid = ""
for i in range(lenID):
nameid += "0"
nameid += id
self.pathID = os.getcwd() + "\\Backup\\Data\\" + nameid
self.pathimages = os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Contacts"
pathlogo = os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Logo"
pathimeeting = os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Meeting"
pathnote= os.getcwd() + "\\Backup\\Data\\" + nameid + "\\Notes.txt"
pathID = os.path.join(os.getcwd() + "\\Backup\\Data\\" + nameid)
####### CREATE FOLDER
if not os.path.exists(pathID):
os.mkdir(pathID)
if not os.path.exists(self.pathimages):
os.mkdir(self.pathimages)
if not os.path.exists(pathlogo):
os.mkdir(pathlogo)
if not os.path.exists(pathimeeting):
os.mkdir(pathimeeting)
if not os.path.exists(pathnote):
os.mkdir(pathnote)
self.ui.label_2.setText(self.pathID)
self.Cargar(self.pathimages)
self.Logo(pathlogo)
self.Notes(self.pathID)
os.mkdir() creates a directory, wheras os.mknod() creates a new filesystem node (file), so you should change the applicable function calls to that.
Alternatively, (due to os.mknod() not being great cross-platform), you can open a file for writing then immediately close it again, thus creating a blank file:
with open(pathnote, 'w'): pass

Create variables from text file in Python

This is linked to this question here I used the first answer, I tried changing the code but it didn't seem to work as that example has "[]" in the variables
I have a text file here:
room1North = CP
room1East = CP
room1South = OP
room1West = OP
room2North = OP
room2East = CP
room2South = EP
room2West = OP
I would like Python to create variables with the values in the text file so the variable "room1North = CP" in Python
I have the following code so far
with open("maze files.txt", "r") as f:
data = f.readlines()
room1North, room1East, room1South, room1West, room2North, room2Eeast, room2South, room2West = [d.split('=')[1].split('\n')[0] for d in data]
I get the following error:
IndexError: list index out of range
You don't actually want separate variables; you want a single dict whose keys are read from the file.
with open("maze files.txt", "r") as f:
data = {k:v for k, v in [line.strip().replace(' ', '').split("=") for line in f]}
# data["room1North"] == "CP"
# data["room1East"] == "CP"
# data["room1South"] == "OP"
# etc
Change your code as bellow
with open("maze files.txt", "r") as f:
data = f.readlines()
room1North, room1East, room1South, room1West, room2North, room2Eeast, room2South, room2West = [d.split('=')[1].split('\n')[0] for d in ''.join(data).split('\n')]
I think you'd have more luck using a dictionary rather than relying on pure variables.
with open("maze files.txt", "r") as f:
data = f.readlines()
rooms = {}
for i in data:
currentRoom = i.replace(' ', '').strip().split('=')
rooms[currentRoom[0]] = currentRoom[1]
What you'll be left with is a dictionary like the following
print(rooms)
#{'room1North ': ' CP', 'room1East ': ' CP', 'room1South ': ' OP', 'room1West ': ' OP', 'room2North ': ' OP', 'room2East ': ' CP', 'room2South ': ' EP', 'room2 West ': ' OP'}
You can reference each room and it's value by rooms["room1North"]

while true loop in python can't be stopped [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem with this loop in python:
i = 1
while True:
with open('/tmp/file.txt', 'r+') as f:
for line in f:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
result = Function()
if "statement" in result:
out = open('/tmp/result.txt', 'a+')
out.write(result)
out.close()
i = i + 10
else:
return i
I want first read file.txt line by line and then for each line count i till statement exists in result but this loop is infinitive... So I removed break and used return i instead. but no result
How can I tell the while True loop to be stopped when all lines from file.txt is read and for each line counter is completed?
UPDATE
what I want to process:
word1line1word2line1counter=1test
word1line1word2line1counter=2test
word1line1word2line1counter=3test
.
.
.
#`till my if condition is true` then
word1line2word2line2counter=1test
word1line2word2line2counter=2test
word1line2word2line2counter=3test
.
.
.
and so on
Thanks
I think you need to switch your loops around:
i = 1
with open('/tmp/file.txt', 'r+') as f:
for line in f:
result = ...
while "statement" in result:
with open('/tmp/result.txt', 'a+') as out:
out.write(result)
i += 10
result = ...
Although it is not at all clear what this algorithm is supposed to be doing
I found the answer:
out = open('/tmp/result.txt', 'a+')
with open('/tmp/file.txt', 'r+') as f:
for line in f:
i = 1
line=line.strip('\r\n ')
while True:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
print work
result = Function()
if "statement" in result:
out.write(result)
i += 10
else:
break
out.close()

Categories