Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
This post was edited and submitted for review 4 days ago.
Improve this question
def _init_(self. row, col, data):
self.child = {}
self.row = row
self.col = col
self.data = data
self.active = True
file = open('filename.txt', 'r')
maze = file.readlines()
n = (intmaze[0])
full = maze[1:(n*n)+1]
file.close
Value error: invalid literal for int() with base 10:'2,1,1,3\n'
I am trying to read a text file with the following matrix
2,1,1,3
2,1,2,3
1,1,2,3
3,G,3,1
You have replace n = int(maze[0]) with the following ->
You have to first store it into list by l = maze.split(",") then you can write n = len(l) to get the length of the matrix.
with open("maze.txt","r") as fd:
maze = [i.split(",") for i in fd.read().splitlines()]
print(len(maze[0]))
print(maze)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
a = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")[1]
b = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")[2]
c = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")[3]
for val1,val2,val3 in zip(a,b,c):
try:
cast_data.append(val1.get_text())
cast_data.append(val2.get_text())
cast_data.append(val3.get_text())
except:
continue
data.append(cast_data)
dataFrame = pd.DataFrame(data = data)
dataFrame.to_csv('sssssssssssss.csv')
print (dataFrame)
Stress! Can you help me out?
My BIG problem is when the index 1 is missing im getting an error how to avoid those error out of range?
i want to improve my poor code please help me
You can check the number of items before accessing to each items in the list:
items = soup3.find('ul',class_="list m-b-0").find_all('li', class_="list-item p-a-0")
if len(items) < 3:
return
a = items[1]
b = items[2]
c = items[3]
...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
This a sample txt file called "price_file.txt":
Apple,$2.55
Banana,$5.79
Carrot,$8.19
Dragon Fruit,$8.24
Eggs,$1.44
Hamburger Buns,$1.89
Ice Pops,$4.42
This is a function to allow the user to read the file:
def addpricefile (price_file):
# input: price file txt
# output: item mapped to its price in a dictionary
global item_to_price
for next_line in price_file:
item,price = next_line.strip().split(',')
item_to_price[item]= float(price[1:]) #map item to price
return item_to_price
p = input ("Enter price file: ")
price_file2 = open(p, "r")
price_file = price_file2.readlines()
for next_line in price_file:
addpricefile(price_file2)
print(item_to_price)
price_file2.close()
However, I get an empty dictionary as the output. How do I fix this?
Try this code, I was a bit confused by what you had there but you can simplify the operation a bit. This will achieve the same result. I hope this helps you solve your problem.
def openAndSeperate(filename):
with open(filename,'r') as file:
priceList = {}
for i in file:
i = i.strip('\n').split(',')
priceList[i[0]] = float(str(i[1])[1:])
return priceList
def main():
filename = 'price_file.txt'#input('Enter File Name: \n')
priceList = openAndSeperate(filename)
print(priceList)
if __name__ == '__main__':
main()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a variable called message.
that variable has value like below:
:1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION
from above variable I want to take only :2A: field contains value
which means I wants only below two line
:2A:/256789422254
TEST VALUE
I tried with
lines = message.readlines()
for index,line in enumerate(lines):
if :2A: in line:
print lines [index+2]
which is not working.
Try this:
s = '''
:1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION
'''
x, y = s[s.index(':2A:') - 1 :].strip().split("\n")[:2]
x = x.split(':')[2]
print(x, y)
Output:
/256789422254 TEST VALUE
message=""":1A:name
:1B:Address
:1C:phone
:2A:/256789422254
TEST VALUE
:2B:/INSTITUTION"""
def solver(lines):
x, y = 0, 0
for i, line in enumerate(lines):
if line.find(':2A:') == 0:
x = i
if line.find(':2B:') == 0:
y = i
break
return lines[x:min(x + 2, y)]
solver(message.split('\n'))
#Output [':2A:/256789422254', 'TEST VALUE']
The solution works by finding the index of ':2A' in the array of lines. It also finds the position of ':2B' in the array. Then it merely returns a slice of the lines in between.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Ok I'm learning read and write files at the moment but I need a little help to sum the numbers in a file.
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
for i in range (the range of int is unknown)
file = sample.read ()
sample.close ()
main ()
You may iterate over the file like this:
for i in sample:
and convert using int() to an integer.
The for loop can be done with map and the sum with sum.
This is the final code:
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
result = sum(map(int, sample))
print(result)
sample.close ()
main ()
What you want is:
for line in sample:
# process the line
If each line just contains an integer, you can simplify it further to sum(map(int, sample)).
To add safety, you should cast your integers with error checking and ensure that the file exists before reading it.
import os
def safecast(newtype, val, default=None):
try:
return newtype(val)
except ValueError:
pass
return default
def sumfile(filename):
if not os.path.isfile(filename):
return None
sum = 0
with open(filename, "r") as file:
for line in file:
sum += safecast(int, line, 0)
return sum
sum = sumfile(r'C:\user\desktop\text.txt')
print(sum)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
[data.txt]
CODE\tUSERNAME\tSPENT\tCOLUM1\tCOLUM2
I want to sort the file [data.txt], using "SPENT". How can i do this?
Yes, of course it is possible. For example:
# read file into array of lines
lines = open("data.txt").readlines()
# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[2])
The lambda extrudes the SPENT column from the row to be used as sorting-key.
def subMenu_5():
# read file into array of lines
lines = open("database").readlines()
# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[3])
clientList = []
dataQuantify = 0
database = open('database','r')
i = 1
while (i == 1):
if (database.readline() == ''):
i = 0
else:
dataQuantify = dataQuantify + 1
database.close()
sortList = open("sortList","w")
for i in range (3):
sortList.write(lines[i])
sortList.close()
print "[Código] [Nome] [Quant. Prod. Comprados] [Valor Gasto] [Descontos] \n"
sortList = open('sortList','r')
i = 0
while (i < dataQuantify):
clientList.append(sortList.readline())
print clientList[i]
i = i + 1
database.close()
raw_input("Precione 'ENTER' para voltar ao menu principal... ")
return
This work! Very Thx!