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

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()

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

Create averages from a list from .txt file?

classs = input("Class [1, 2 or 3] - ")
if clas
data = f.readlines()
for le:
print(line)
found = True
if found == False:
print("False")
Here is a typical printed output:
John = 10
John = 6
John = 4
I need to be able to create an average just by using the 10, 4, 6 as I need to know a way to isolate the rest and allow the numbers to proceed inorder to create the average score.
If the format of each line is the same, you can use string.split and cast to int:
classs = input("Class [1, 2 or 3] - ")
l = []
if classs =='1':
name = input("What is your name? - ")
datafile = '1.txt'
found = False
with open(datafile, 'r') as f:
data = f.readlines()
for line in data:
if name in line:
print(line)
l.append(int(line.split()[2]))
found = True
if found == False:
print("False")
Then go through the list of numbers and get the average, something like:
total = 0
num = 0
for x in l:
total = total + x
num = num + 1
print(total/num)
one way would be to extract the last 3 numbers for each player from your list (i'm assuming you only need 3, if not this code can be altered for more)
Class = input("Class: ")
dataList = []
file = open('class ' + str(Class) + '.txt', "r")
for line in file:
count = 0
record = line
studentList = record.split(': ')
score = studentList[1].strip('\n')
studentList = [studentList[0], score]
if len(dataList) == 0:
dataList.append(studentList)
else:
while count < len(dataList):
if studentList[0] == dataList[count][0]:
if len(dataList[count]) == 4:
dataList[count][3] = dataList[count][2]
dataList[count][2] = dataList[count][1]
dataList[count][1] = score
break
dataList[count].append(score)
break
elif count == len(dataList) - 1:
dataList.append(studentList)
break
count = count + 1
this will give you a 2D array. each smaller array within will conatin the persons name at index 0 and there three numbers at indecies 1,2 and 3. now that you have these, you can simply work out the average.
AverageScore = []
# this is the array where the student' record (name and highest score) is saved
# in a list
count = 0
while count < len(dataList):
entry = []
# this is whre each student name and score will be temporarily held
entry.append(dataList[count][0])
# this makes it so the array 'entry' contains the name of every student
Sum = 0
frequency = len(dataList[count])
incount = 1
while incount < frequency:
Sum = Sum + int(dataList[count][incount])
incount = incount + 1
average = Sum / (frequency-1)
entry.append(average)
AverageScore.append(entry)
# this appends the name and average score of the student to the larger array
# 'AverageScore'
count= count + 1
# the count is increased so the process is repeated for the next student
AverageSorted = sorted(AverageScore,key=lambda l:l[1], reverse=True)
# http://stackoverflow.com/questions/18563680/sorting-2d-list-python
# this is code i obtained through someone else's post which arranges the array in descending
# order of scores
count2 = 0
while count2 < len(AverageSorted):
print(AverageSorted[count2][0], ':', AverageSorted[count2][1])
count2 = count2 + 1
# this formats the array so it prints the elements in a list of each student's
# name and score
Long winded and inefficient, but its the best i can do with my small knowledge of python :)
If this is the content of 1.txt:
John = 1
Joe = 3
John = 7
Joe = 9
Bob = 3
Joe = 8
John = 2
Bob = 9
Roger = 13
Replace your "with" statement with this:
name = "John"
_class = 1
with open("%s.txt" % _class, "r") as out:
lines = out.readlines()
scores = []
for line in lines:
if name in line:
# "strip" without arguments strips out all beginning
# and trailing white-space (i.e. " ", "\n", "\r").
line = line.strip()
score = int(line.split(" = ")[1])
scores.append(score)
# If there isn't any scores in this list, then there was no user
# data.
if scores:
# Use python built-in sum to sum the list of scores and
# divide the result by the number of scores gives you the average.
average = sum(scores) / len(scores)
print "%s's average score is %.1f out of %d game(s)." % (
name, average, len(scores))
else:
print "User %s not found." % name

histogram chops off after 10 on the horizontal axis

My program creates a histogram from a dictionary. It first reads in text from a text file. Then it counts and prints out the length of each word. For example, the words "in", "the", and "Florida" would produce a count like this.
Length Count
2 1
3 1
7 1
Because there are only 1 word of length 2, 1 word of length 3 and 1 word of length 7. My text file has hundreds of words. So, there are some words that are of length 10 and greater. But after 10 on the horizontal axis it doesn't show anything. Please help. Below is my code.
import sys
import string
def rem_punc(w):
plst = list(string.punctuation)
for p in plst:
if p in w:
w = w.replace(p,'')
return w
def word_length_processor(text):
d = dict()
for w in text:
w = rem_punc(w)
if len(w) > 0:
n = len(w)
if n not in d:
d[n] = 1
else:
d[n] = d[n] + 1
for k,v in d.items():
print("{0} {1}".format(k,v))
print()
hist_maker(d)
def hist_maker(d):
freq = d
for y in range(300,9,-10):
print ("{:>6} | ".format(y), end="")
for x in range(1,10):
if freq.get(x,0) >= y:
column = "***"
else:
column = " "
print(column, end="")
print()
print(" ------------------------------------------------------")
print(" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15")
arg_string = sys.argv[1]
try:
f = open(arg_string, 'r')
except:
print('Could not open file. Please try again.')
sys.exit()
text = f.read()
f.close()
text = text.split()
print("{0} {1}".format("Length","Count"))
print(word_length_processor(text))

Why does this variable an empty sequence?

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.

Calculating average of numbers in a file

So what I have to do is figure out how to ask a user for a a text file and output the average of all the numbers. By tinkering around I have figured out how to find the average of a list i made but not sure how to do a list that the user give me. This is what I have right now:
with open('average', 'wt') as myFile:
myFile.write('3\n')
myFile.write('45\n')
myFile.write('83\n')
myFile.write('21\n')
with open('average', 'rt') as myFile:
total, n = 0, 0
for line in myFile:
total += int(line)
n += 1
print(float(total) / n)
Supposing that there is one number on each line of the file:
with open(input('Filename: '), 'r') as f:
numbers = [int(a.strip()) for a in f]
print('Average is {}'.format(sum(numbers)/len(numbers)))
Something like this?
import string
fileName = raw_input("What file name: ")
lines = []
try:
file = open(fileName)
lines = file.readlines()
file.close()
except:
print "Unable to open file"
sum = 0
values = 0
if(len(lines) > 0):
for line in lines:
value = 0
try:
value = int(string.strip(line))
except ValueError:
pass
if(value != 0):
sum = sum + value
values += 1
print "Average = %f for %d lines, sum = %f"%(sum/values,values,sum)
else:
print "No lines in the file"
NOTE: This assumes one number per line. It will not count blank lines or lines that have text. Other than that, junk on the lines or a bad file should not cause an exception, etc.
This was the test file (there are blank lines):
10
20
30
40
50
23
5
asdfadfs
s
And the output:
What file name: numbers.txt
Average = 25.000000 for 7 lines, sum = 178.000000

Categories