Why does this variable an empty sequence? - python

The code i am using is selecting the highest number out of three in a text file set out as
R 3 5 7
F 2 9 6
I 6 3 5
When it is run it does wright the correct infomation to the text file but comes up with
max_in_line = max(nums)
ValueError: max() arg is an empty sequence
my code is
with open (classno, 'r') as f, open("class11.txt", 'w') as fout:
for line in f.readlines(): #does right swaps around
if not line.strip(): continue
parts = line.split()
nums_str = line.split()[1:]
nums = [int(n) for n in nums_str]
max_in_line = max(nums)
print (max_in_line)
print (line)
score = (max_in_line)#same problem
name = (parts[0])
fout.write(("\n") + str(score) + (" ") + (name))
fout.close
f.close#it does write them but comes up with the problem

Try this code, just skip the empty line or empty element in the list:
with open ('classno.txt', 'r') as f, open("class11.txt", 'w') as fout:
lines = [line.strip() for line in f]
for line in lines:
splitted = [i for i in line.split(' ') if i]
nums = splitted[1:]
max_nums = max(map(int, nums))
name = splitted[0]
fout.write('\n' + str(max_nums) + ' ' + name)
It works for me, hope helps.

Related

How to print specific lines from a text file in python

Ive made code that lets me write in numbers in lines, but now, out of all the numbers i get I have to make the comp. print the ones that are nicely divisible by 2 So far this is what ive got:
i = 0
x = 1
y = 0
z = 20
My_file = open("Numbers", 'w')
while i < z:
My_file.write(str(x))
My_file.write("\n")
x = x + 1
i = i + 1
My_file.close()
i = 0
My_file = open("Numbers", 'r')
for line in My_file:
if int(My_file.readline(y)) % 2 == 0:
print(My_file.readline(y))
y = y + 1
The top part work, my problem is the one int(My_file.readline(y)) % 2 == 0 is crap, it says:
invalid literal for int() with base 10: ''.
Each line contains a line break ("2\n"), you need to remove \n before converting to number:
...
My_file = open("Numbers", 'r')
for line in My_file:
line = line.strip() # removes all surrounding whitespaces!
if int(line) % 2 == 0:
print(line)
y = y + 1
Out:
2
4
6
8
10
12
14
16
18
20
Based on previous answers, here's a fully working example:
start_value = 1
max_value = 12
filename = "numbers"
with open(filename, "w") as my_file:
value = start_value
while value <= max_value:
my_file.write(f"{value}\n")
value += 1
with open(filename, "r") as my_file:
lines = my_file.readlines()
for line in lines:
line = line.strip()
if int(line) % 2 == 0:
print(line)
This code makes use of the "context manager" of python (the with keyword). Used with open(), it handles nicely the closing of the file.
Your error came from a \n at the end of each number. The conversion from str to int didn't work because the interpreter couldn't find out how to convert this character.
As a good practice, use meaningful variables names, even more when you ask questions here: it helps people understanding the code faster.
Does this help:
MAXINT = 20
FILENAME = 'numbers.txt'
with open(FILENAME, 'w') as outfile:
for i in range(1, MAXINT+1):
outfile.write(f'{i}\n')
with open(FILENAME) as infile:
for line in infile:
if int(line) % 2 == 0:
print(line, end='')
This works:
FILE_NAME = 'Numbers.txt'
MAX_NUMBER = 20
with open(FILE_NAME, 'w') as file:
numbers = list(map(str, range(MAX_NUMBER)))
for n in numbers:
file.write(n)
file.write('\r')
with open(FILE_NAME, 'r') as file:
for number in file:
if int(number) % 2 == 0:
print(number, end='')
Output:
0
2
4
6
8
10
12
14
16
18

How to only print or get the second result

I only want to get the second result, which num prints and use it.
savee1 is a .txt file
def copycoordinates():
savee1 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles", title="Choose FIRST File", filetypes=[("sii files", "*.sii")])
savee2 = filedialog.askopenfilename(initialdir="C:/USERS/" + username + "/documents/Euro Truck Simulator 2/profiles", title="Choose SECOND File", filetypes=[("sii files", "*.sii")])
i1 = Label(frame5, text="Chosen FIRST File \n" + savee1)
i1.pack()
i2 = Label(frame5, text="Chosen SECOND File \n" + savee2)
i2.pack()
command=lambda:[save1()]
subprocess.Popen(["C:/SII_Decrypt.exe", savee1])
command=lambda:[save2()]
subprocess.Popen(["C:/SII_Decrypt.exe", savee2])
#time.sleep(1)
with open(savee1, "r+") as save1:
for num, line in enumerate(save1, 1):
if "truck_placement:" in line:
print(num)
If you mean you want the second match, you can try:
with open(savee1, "r+") as save1:
match = 0
for num, line in enumerate(save1, 1):
if 'truck_placement:' in line:
match += 1
if match == 2
print(num)
else:
continue
The num will print on the second match.
There are definitely better ways, but this is one of the most easy solution.
results = list()
with open(savee1, "r+") as save1:
for num, line in enumerate(save1, 1):
if "truck_placement:" in line:
print(num)
results.append(num)
print(results[1]) #this is the value you want
not sure what's in your text file, but usually things are separated in some way (line break, tab separated, comma separated). You should split on what ever it is that separates and then you can just index the resulting list. the following code assumes the things you want are separated by new lines:
with open(save1, "r+") as infile:
f=infile.read()
list_o_txt = f.split('\n')
print (list_o_txt[1])
if you want to make a sublist of texts that only contain a phrase 'truck_placement'
with open(save1,'r') as infile:
f=infile.read()
list_o_txt = f.split('\n') # produces a list
filtered_list = [line for line in list_o_txt if 'truck_placement' in line] #filters the list
print (filtered_list[1]) #prints the second item

Read First 10 Lines in a File; If Shorter Only Read Those Lines

I want to open a file, and read the first 10 lines of a file. If a file has less than 10 lines it should read as many lines as it has. Each line has to be numbered, wether it's text or it's whitespace. Because I have to strip each line, I can't differentiate between an empty string, and the end of a file. For example if I read a file with only three lines, it will print out lines 1 - 10, with lines 4 - 10 being empty, but I would like to have it stop after reaching that 3rd line, as that would be the end of the file. I would really appreciate any help, thank you.
def get_file_name():
fileName = input('Input File Name: ')
return fileName
def top(fileName):
try:
file = open(fileName, 'r')
line = 'text'
cnt = 1
while cnt <= 10:
if line != '':
line = file.readline()
line = line.rstrip('\n')
print(str(cnt) + '.', line)
cnt += 1
else:
line = file.readline()
line = line.rstrip('\n')
print(str(cnt) + '.', line)
cnt += 1
file.close()
except IOError:
print('FILE NOT FOUND ERROR:', fileName)
def main():
fileName = get_file_name()
top(fileName)
main()
def read_lines():
f = open("file-name.txt","r")
num = 1
for line in f:
if num > 10:
break
print("LINE NO.",num, ":",line)
num = num + 1
f.close()
Here, the loop exits at the end of the file. So if you only had 7 lines, it will exit automatically after the 7th line.
However, if you have 10 or more than 10 lines then the "num" variable takes care of that.
EDIT: I have edited the print statement to include the line count as well and started the line count with 1.
with open(filename, 'r') as f:
cnt = 1
for line in f:
if cnt <= 10:
print(str(cnt) + '.', line, end='')
cnt += 1
else:
break
This should do exactly what you need. You can always remove the if/else and then it will read exactly however many lines are in the file. Example:
with open(filename, 'r') as f:
cnt = 1
for line in f:
print(str(cnt) + '.', line, end='')
cnt += 1
You can try to load all the lines into array, count the total line and use an if statement to check if total is 10 or not, then finally use a for loop like for i in range (0,9): to print the lines.

how to shift values to the next line in a txt file

I have a txt file with floats separated by blank space I need to to keep only 4 elements in each line. I tried to calculate blankspace. Now i need to shift the rest of the values to the next line and restart.
fname = open("file.txt", 'r')
text = fname.read()
countBlank=0
for line in text:
for char in line:
if char.isspace():
countBlank += 1
if countBlank ==4
You can do it by converting your data and storing it in an array then you can output it to a new file like this:
import numpy as np
fname = open("file.txt", 'r')
text = fname.read()
arr = np.array(text.split())
rows = len(arr) // 4
remain = len(arr) % 4
out = np.full((rows+1, 4), None).astype(float)
out[:rows, :] = arr[:-remain]
out[rows, :remain] = arr[len(arr)-remain:]
np.savetxt('file2.txt', out)
Try this, works for me.
floatlist = fname.read().split(" ")
count = 0
finalstring = ""
for x in floatlist:
count += 1
if count == 4:
finalstring += x + "\n"
else:
finalstring += x + " "
Input:
"1 2 3 4 5 6 7 8"
Output:
"1 2 3 4
5 6 7 8"
How to write into file: (on the end of the existing code)
fname.close()
fname = open("file.txt", "w")
fname.write(finalstring)
fname.close()

How to make automated writer to append lines in Python

Here is my Code :
b = 1
a = "line"
f = open("test.txt", "rb+")
if a + " " + str(b) in f.read():
f.write(a + " " + str(b + 1) + "\n")
else:
f.write(a + " " + str(b) + "\n")
f.close()
It prints now line 1 and then line 2, but how can i make this read what is the last "line x" and print out line x + 1?
for example:
test.txt would have
line 1
line 2
line 3
line 4
and my code would append line 5 in the end.
I was thinking maybe some kind of "find last word" kind of code?
How can I do this?
If you know for certain that every line has the format "word number" then you could use:
f = open("test.txt", "rb+")
# Set l to be the last line
for l in f:
pass
# Get the number from the last word in the line
num = int(l.split()[-1]))
f.write("line %d\n"%num)
f.close()
If the format of each line can change and you also need to handle extracting numbers, re might be useful.
import re
f = open("test.txt", "rb+")
# Set l to be the last line
for l in f:
pass
# Get the numbers in the line
numstrings = re.findall('(\d+)', l)
# Handle no numbers
if len(numstrings) == 0:
num = 0
else:
num = int(numstrings[0])
f.write("line %d\n"%num)
f.close()
You can find more efficient ways of getting the last line as mentioned here What is the most efficient way to get first and last line of a text file?

Categories