Python continue for loop from file - python

I have a code that generates characters from 000000000000 to ffffffffffff which are written to a file.
I'm trying to implement a check to see if the program was closed so that I can read from the file, let's say at 00000000781B, and continue for-loop from the file.
The Variable "attempt" in (for attempt in to_attempt:) has tuple type and always starting from zero.
Is it possible to continue the for-loop from the specified value?
import itertools
f = open("G:/empty/last.txt", "r")
lines = f.readlines()
rand_string = str(lines[0])
f.close()
letters = '0123456789ABCDEF'
print(rand_string)
for length in range(1, 20):
to_attempt = itertools.product(letters, repeat=length)
for attempt in to_attempt:
gen_string = rand_string[length:] + ''.join(attempt)
print(gen_string)

You have to store the value on a file to keep track of what value was last being read from. I'm assuming the main for loop running from 000000000000 to ffffffffffff is the to_attempt one. All you need store the value of the for loop in a file. You can use a new variable to keep track of it.
try:
with open('save.txt','r') as reader:
save = int(reader.read())
except FileNotFoundError:
save = 0
#rest of the code
for i in range(save,len(to_attempt)):
with open('save.txt','r') as writer:
writer.write(i)
#rest of the code

Related

Why does my output display turn 1 instead of turn 11 when I load game after saving?

image of output after saving and loading turn 11
def save_game(buildings,building_count,turn):
f = open('data.txt', 'w')
f.write('Turn {}\n'.format(turn))
for i in range(len(board)):
s = ''
for j in range(len(board[i])):
s += board[i][j] + ','
f.write(s[:-1] + '\n')
f.close()
return buildings, building_count, turn
def load_game(buildings, building_count, turn):
f = open('data.txt','r')
f.readline()
for line in f:
data = line.strip('\n').split(',')
board.append(data)
f.close()
return buildings, building_count, turn
Please help me using file i\o, this is a school assignment and I am not allowed to use imports or anything, thank you so much!
Your load game doesn't change the input parameters buildings, building_count, turn in any way.
I would suspect 1 is just the default value or a random initialized value for turn, when you call the load_game function.
You append something into board, wherever that is from. So the code in general seems wrong.
As a start I would not pass any parameters except maybe the file path to load_game. Initialize the variables in there and fill them with the correct values.
Regarding the turn count problem specifically:
For the first line you can read it in, split it into to parts by using .split(' '). check if the first entry in the list is equal to 'Turn' and read in the second one and parse it to an int.

Python Sorted, Not Sorting Data

I have a very simple program to sort data and write it to a text file, but the sorted method is not doing what it should be. Instead the values are entering the array and text file in the order I input them. Can anyone quickly explain why?
import os
import os.path
values = []
#for value in values:
data = 1
while data:
data = input('Enter the values. Press enter to confirm values:')
if data:
values.append(data)
else:
data = data
print(sorted(values))
sort = sorted(values)
print(sort)
name = open("sortedvalues.txt", "a+") #opens file usernames.txt and gets ready to write to it
file = str(sort) #converts the values to a string and writes them to the file
name.write('\n' + file) #writes contents in file to usernames.txt
name.close() #closes file
open1 = open("sortedvalues.txt", "r") #opens file to read it
print('reading')
print (open1.read()) #prints whatever is in the text file
I could not recreate your issue. The below code is works fine, sorts the given bunch of numbers correctly and writes to file.
Also you are sorting array twice, I just corrected it.
values = []
sorted_values = []
data = 1
while data:
data = input('Enter the values. Press enter to confirm values:')
if data:
values.append(data)
else:
data = data
# here you are sorted it first and second outside of while loop
sorted_values = sorted(values)
print(sorted_values)
print(sorted_values)
with open("sortedvalues.txt", "a+") as name:
name.write('\n' + str(sorted_values))
with open("sortedvalues.txt", "r") as open1:
print('reading')
print (open1.read())
inputs:
5
3
4
2
1
0
inside file:
[1, 2, 3, 4, 5]
#JohnGordon answered the question in a below comment. The issue was not with the way the code was working, as improper as it may be. The problem is that the integer values are actually being taken as strings and sorting as if they were strings. The input values first need to be converted before being sorted.
Edit I should add that specifying the input as an integer results in a traceback because null (when the user presses enter to confirm the entered values) can not be parsed as an integer. To work around this, I simply added
while data:
data = input('Enter the values. Press enter to confirm values:')
if data:
values.append(int(data))
else:
data = data
print(sorted(values))
Specifically, in the if data:portion, specifying to append data as an int to the list solves the problem and the sorted or .sort() methods work correctly.

Array visibility in python

Simple question: i've got this code:
i want to fetch a row with Dictreader from the csv package, every entry i wanto to cast it float and put it in the data array. At the end of the scanning i want to print the first 10 elements of the array. It gives me error of visibility on the array data.
with open(train, "r") as traincsv:
trainreader = csv.DictReader(traincsv)
for row in trainreader:
data = [float(row['Sales'])]
print(data[:10])
If i put the print inside the for like this
with open(train, "r") as traincsv:
trainreader = csv.DictReader(traincsv)
for row in trainreader:
data = [float(row['Sales'])]
print(data[:10])
It prints all the entries not just 10.
You are overwriting data every time in the for loop. This is the source of your problem.
Please upload an example input for me to try and I will, but I believe what is below will fix your problem, by appending to data instead of overwriting it.
Also, it is good practice to leave the with block as soon as possible.
# Open with block and leave immediately
with open(train, "r") as traincsv:
trainreader = csv.DictReader(traincsv)
# Declare data as a blank list before iterations
data =[]
# Iterate through all of trainreader
for row in trainreader:
data.append([float(row['Sales'])])
# Now it should print first 10 results
print(data[:10])
Ways of appending a list:
data = data + [float(row['Sales'])]
data += [float(row['Sales'])]
data.append([float(row['Sales'])]

Writing sublists in a list of lists to separate text files

I’m really new to Python but find myself working on the travelling salesman problem with multiple drivers. Currently I handle the routes as a list of lists but I’m having trouble getting the results out in a suitable .txt format. Each sub-list represents the locations for a driver to visit, which corresponds to a separate list of lat/long tuples. Something like:
driver_routes = [[0,5,3,0],[0,1,4,2,0]]
lat_long =[(lat0,long0),(lat1,long1)...(latn,longn)]
What I would like is a separate .txt file (named “Driver(n)”) that lists the lat/long pairs for that driver to visit.
When I was just working with a single driver, the following code worked fine for me:
optimised_locs = open('Optimisedroute.txt', 'w')
for x in driver_routes:
to_write = ','.join(map(str, lat_long[x]))
optimised_locs.write(to_write)
optimised_locs.write("\n")
optimised_locs.close()
So, I took the automated file naming code from Chris Gregg here (Printing out elements of list into separate text files in python) and tried to make an iterating loop for sublists:
num_drivers = 2
p = 0
while p < num_drivers:
for x in driver_routes[p]:
f = open("Driver"+str(p)+".txt","w")
to_write = ','.join(map(str, lat_long[x]))
print to_write # for testing
f.write(to_write)
f.write("\n")
f.close()
print "break" # for testing
p += 1
The output on my screen looks exactly how I would expect it to look and I generate .txt files with the correct name. However, I just get one tuple printed to each file, not the list that I expect. It’s probably very simple but I can't see why the while loop causes this issue. I would appreciate any suggestions and thank you in advance.
You're overwriting the contents of the file f on every iteration of your for loop because you're re-opening it. You just need to modify your code as follows to open the file once per driver:
while p < num_drivers:
f = open("Driver"+str(p)+".txt","w")
for x in driver_routes[p]:
to_write = ','.join(map(str, lat_long[x]))
print to_write # for testing
f.write(to_write)
f.write("\n")
f.close()
p += 1
Note that opening f is moved to outside the for loop.

Trying to write python CSV extractor

I am complete newbie for programming and this is my first real program I am trying to write.
So I have this huge CSV file (hundreds of cols and thousands of rows) where I am trying to extract only few columns based on value in the field. It works fine and I get nice output, but the problem arises when I am try to encapsulate the same logic in a function.
it returns only first extracted row however print works fine.
I have been playing for this for hours and read other examples here and now my mind is mush.
import csv
import sys
newlogfile = csv.reader(open(sys.argv[1], 'rb'))
outLog = csv.writer(open('extracted.csv', 'w'))
def rowExtractor(logfile):
for row in logfile:
if row[32] == 'No':
a = []
a.append(row[44])
a.append(row[58])
a.append(row[83])
a.append(row[32])
return a
outLog.writerow(rowExtractor(newlogfile))
You are exiting prematurely. When you put return a inside the for loop, return gets called on the first iteration. Which means that only the firs iteration runs.
A simple way to do this would be to do:
def rowExtractor(logfile):
#output holds all of the rows
ouput = []
for row in logfile:
if row[32] == 'No':
a = []
a.append(row[44])
a.append(row[58])
a.append(row[83])
a.append(row[32])
output.append(a)
#notice that the return statement is outside of the for-loop
return output
outLog.writerows(rowExtractor(newlogfile))
You could also consider using yield
You've got a return statement in your function...when it hits that line, it will return (thus terminating your loop). You'd need yield instead.
See What does the "yield" keyword do in Python?

Categories