I am having hard time to understand how to properly inert values into my variables from txt file. First line is number of test cases, then goes number of houses and then house binary string. Here are my input values:
2 (Number of tests [INT])
3 (Number of houses [INT])
111 (Binary string [String])
6 (Number of houses [INT])
100100 (Binary string [String])
I know we can do like this:
test_cases = int(input())
for i in range(test_cases):
house_number = int(input())
house_string = input()
some_function(int value1, string value2)
But I want to create txt file so I will not type these values every time. I know how to open and read txt file. However can not imagine how can I pass variables.
with open('test.txt') as file:
lines = file.readlines()
for line in lines:
...
As long as your text file is consistent with formatting you can loop over every two elements and turn them into a list of tuples. Note that this code excludes the first element assuming there are complete pairs:
with open('test.txt') as file:
output_lst = []
lines = file.readlines()
for i,k in zip(lines[1::2], lines[2::2]):
output_lst.append((int(i), str(k)))
Related
I have a program that saves a .txt log with multiple values and text. Those are time values can differ each time the program is ran, but their place in this .txt file is always the same. I need to grab those values and check if they are smaller than 6 seconds. I was trying to convert my .txt file to string, and then use:
x = string(filename[50:55])
float(x)
But it doesn't seem to work. How can I extract values form fixed place in .txt file and then convert them to float number?
//EDIT:
Photo of my log below, I want to check those values marked with blue line:
//EDIT2:
Photo of another log, how would I extract those percentages, those must be below 70 to pass.
//EDIT3:Photo of the error I got and fragment of the code:
with open(r'C:\Users\Time_Log.txt') as f:
print(f)
lines = f.readlines()
print(r'Lines: ')
print(lines)
print(r'Type of lines:', type(lines))
# start at 1 to avoid the header
for line in range(1, len(lines)):
print(r'Type of line:', type(line))
splits = line.split("|")
print(r'Type of splits:', type(splits))
t = splits[3].split(".")
if t[0] < 6:
print(r'Test completed. Startup time is shorter than 6 seconds')
I mean with an example it would be much simpler, but assuming that your values have a fixed distance (idk space or tab) you'd split the string with that and look at the elements that you want to compare, so idk if the time is your 6th item you'd string.split(" ") and pick splitted_str[5]. You can do that further if you're time format follows a regular pattern idk hours:minutes:seconds and then do the math or you could even use packages like date or time to convert them to some time object which could potentially do some more useful comparison.
So the question is basically how well formatted your values are.
Edit:
So given the example you could:
with open("filename.txt") as f:
lines = f.readlines()
# start at 1 to avoid the header
for i in range(3, len(lines)):
splits = lines[i].split("|")
t = str(splits[3]).split(".")
if int(t[0)] < 6:
[do something with that line]
i'm looking for advice on how to create a script that will search a file for a key word.
My text file looks like this
1,1467800,968.00,957.00,8850,1005,963,546,950,8.00,
0.00,202149.00,12,
1,146928,1005,97995.00,979.00,967.000,824,955,826,
1,147,957.00,883.00,
it's from a Bluetooth device that I was having trouble with them talking over each other my solution was to make one device send a float the other send an int. I'm now trying to separate the numbers, and place them in 2 separate text documents. are there any functions I can do to make this project easier?
This is my current code that just takes in my text file
f = open("file.txt","r")
f1 = open("output.txt","w")
text = ""
for line in f:
text = line
text = text.rstrip("\n")
print(text)
f1.close()
f.close()
my_list = text.split(",")
ints, floats = []
for item in my list:
if '.' in item: #(if float)
floats.append(float(item))
else:
ints.append(int(item))
Explanation:
Split funtion converts text into a list by splitting it into elements using given key. (comma in this case)
Then you can write them into two different documents. For the sake of simplicity I divided them into two other lists which you can use to write a new file.
If your floats are not all actually integers, you can use the is_integer function of float and list comprehensions:
with open('your_file') as fd:
numbers = fd.read().split(',')
floats = [float(num) for num in numbers if not float(num).is_integer()]
integers = [float(num) for num in numbers if float(num).is_integer()]
You can also convert the numbers to a set after getting the floats and substract it from the original numbers list.
Otherwise:
with open('your_file') as fd:
numbers = fd.read().split(',')
floats = [float(num) for num in numbers if '.' in num]
integers = [float(num) for num in numbers if float(num).is_integer()]
I've a file which have integers in first two columns.
File Name : file.txt
col_a,col_b
1001021,1010045
2001021,2010045
3001021,3010045
4001021,4010045 and so on
Now using python, i get a variable var_a = 2002000.
Now how to find the range within which this var_a lies in "file.txt".
Expected Output : 2001021,2010045
I have tried with below,
With open("file.txt","r") as a:
a_line = a.readlines()
for line in a_line:
line_sp = line.split(',')
if var_a < line_sp[0] and var_a > line_sp[1]:
print ('%r, %r', %(line_sp[0], line_sp[1])
Since the file have more than million of record this make it time consuming. Is there any better way to do the same without a for loop.
Since the file have more than million of record this make it time
consuming. Is there any better way to do the same without a for loop.
Unfortunately you have to iterate over all records in file and the only way you can archive that is some kind of for loop. So complexity of this task will always be at least O(n).
It is better to read your file linewise (not all into memory) and store its content inside ranges to look them up for multiple numbers. Ranges store quite efficiently and you only have to read in your file once to check more then 1 number.
Since python 3.7 dictionarys are insert ordered, if your file is sorted you will only iterate your dictionary until the first time a number is in the range, for numbers not all all in range you iterate the whole dictionary.
Create file:
fn = "n.txt"
with open(fn, "w") as f:
f.write("""1001021,1010045
2001021,2010045
3001021,3010045
garbage
4001021,4010045""")
Process file:
fn = "n.txt"
# read in
data = {}
with open(fn) as f:
for nr,line in enumerate(f):
line = line.strip()
if line:
try:
start,stop = map(int, line.split(","))
data[nr] = range(start,stop+1)
except ValueError as e:
pass # print(f"Bad data ({e}) in line {nr}")
look_for_nums = [800, 1001021, 3001039, 4010043, 9999999]
for look_for in look_for_nums:
items_checked = 0
for nr,rng in data.items():
items_checked += 1
if look_for in rng:
print(f"Found {look_for} it in line {nr} in range: {rng.start},{rng.stop-1}", end=" ")
break
else:
print(f"{look_for} not found")
print(f"after {items_checked } checks")
Output:
800 not found after 4 checks
Found 1001021 it in line 0 in range: 1001021,1010045 after 1 checks
Found 3001039 it in line 2 in range: 3001021,3010045 after 3 checks
Found 4010043 it in line 5 in range: 4001021,4010045 after 4 checks
9999999 not found after 4 checks
There are better ways to store such a ranges-file, f.e. in a tree like datastructure - research into k-d-trees to get even faster results if you need them. They partition the ranges in a smarter way, so you do not need to use a linear search to find the right bucket.
This answer to Data Structure to store Integer Range , Query the ranges and modify the ranges provides more things to research.
Assuming each line in the file has the correct format, you can do something like following.
var_a = 2002000
with open("file.txt") as file:
for l in file:
a,b = map(int, l.split(',', 1)) # each line must have only two comma separated numbers
if a < var_a < b:
print(l) # use the line as you want
break # if you need only the first occurrence, break the loop now
Note that you'll have to do additional verifications/workarounds if the file format is not guaranteed.
Obviously you have to iterate through all the lines (in the worse case). But we don't load all the lines into memory at once. So as soon as the answer is found, the rest of the file is ignored without reading (assuming you are looking only for the first match).
I want to take a number, in my case 0, and add 1, then replace it back into the file. This is what I have so far:
def caseNumber():
caseNumber = open('caseNumber.txt', "r")
lastCase = caseNumber.read().splitlines()[0]
Case = []
Case.append(lastCase)
newCase = [ int(x)+1 for x in Case ]
with open('caseNumber.txt', mode = 'a',
encoding = 'utf-8') as my_file:
my_file.write('{}'.format(newCase))
print('Thankyou, your case number is {}, Write it down!'.format(newCase))
After this is run, i get:
this is what is added to the file: 0000[1] (the number in the file was 0000
to start off with, but it added [1] aswell)
Basically, the part I am stuck on is adding 1 to the number without the brackets.
newCase is a list, which gets printed with its values enclosed in brackets. If you just want the value in the list to get written to the file, you'll need to say that.
You don't need to create a list comprehension since you only need 1 item.
Since you're converting list to string you get the list representation: with brackets.
Note that it's not the only problem: you're appending to your text file (a mode), you don't replace the number. You have to write the file from scratch. But for that, you have to save full file contents when reading the first time. My proposal:
with open("file.txt") as f:
number,_,rest = f.read().partition(" ") # split left value only
number = str(int(number)+1) # increment and convert back to string
with open('file.txt',"w") as f:
f.write(" ".join([number,rest])) # write back file fully
So if the file contains:
0 this is a file
hello
each time you run this code above, the leading number is incremented, but the trailint text is kept
1 this is a file
hello
and so on...
I have a text file which reads:
name,number,number,number
name,number,number,number
...
and I want to create a dictionary from it. I found this bit of code:
file = open('Results.txt', 'r')
lines = file.read().splitlines()
s = {lines[i]:[float(k) for k in lines[i+1:i+4]] for i in range(0,len(lines),4)}
However it only works for files with this format:
name
number
number
number
name
number
number
number
...
How can I make it work from my format? Also, is it possible to make it still work if there are less than 3 numbers after the name?
The following will handle lines with one or more comma-separated numbers following a name on each line of the file:
with open('Results.txt') as file:
s = {items[0]: [float(item) for item in items[1:]]
for items in (line.split(',') for line in file)}