How to convert txt file into list of integers - python

First, I have my txt file data here as:
51
2
2
49
15
2
1
14
I would like to convert them into a list to do further calculation, however I couldn't do it and I try to print it one by one by using for loop. Then the error message "Attributes error" kept showing up.
def main():
file = str(input("Please enter the full name of the desired file(with extension) at the prompt below: \n"))
print (get_value(file))
def get_value(file):
file_open = open(file,"r")
print (file_open.read())
a = len(file)
print ("Length =",a)
for line in range file_open:
print (line)
main()

def main():
file = str(input("Please enter the full name of the desired file(with extension) at the prompt below: \n"))
print (get_value(file))
def get_value(file):
file_open = open(file,"r")
lsLines = file_open.readlines()
lsLines = [int(x) for x in lsLines if len(x.strip()) > 0]
file_open.close()
return lsLines
main()

EDIT: wrong language.
with open("file.txt") as f:
ints = [int(line) in f.readlines()]

Related

Why does my program ask for input that comes second?

So I've written a simple program that allows user to enter a line they would like to edit and text they would like to put into that line
def edit_line(file):
a_file = open(file, 'r')
list_of_lines = a_file.readlines()
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
a_file = open(file, 'w')
a_file.writelines(list_of_lines)
a_file.close()
edit_line('sample.txt')
When I run the program it works fine. However, It asks the user to input the text first and the line number second.
What is the reason for this and how can I fix it?
If you want to fix the problem, just split the one line into two:
Instead of:
list_of_lines[int(input('What line would you like to edit?: ')) - 1] = input('Write your text here: ') + '\n'
Do:
index = int(input('What line would you like to edit?: ')) - 1
list_of_lines[index] = input('Write your text here: ') + '\n'
And as the answer #Guy linked explains, when you are doing an assignment line of code, the right hand (value of the variable) is run before the left side.
Validation is everything! What would happen if the user's input for the line number wasn't within the range of lines read from the file?
Here's a more robust approach:
def edit_line(filename):
with open(filename, 'r+') as file:
lines = file.readlines()
while True:
try:
lineno = int(input('What line would you like to edit: '))
if 0 <= lineno < len(lines):
lines[lineno] = input('Write your text here: ') + '\n'
file.seek(0)
file.writelines(lines)
file.truncate()
break
else:
raise ValueError('Line number out of range')
except ValueError as e:
print(e)
edit_line('edit.txt')

How to replace/change element in txt.file

Im trying to replace a cetain element in a txt file.
let say that if i find the name in telephonelist.txt, i want i to change the number to this person with the input value of newNumber.
let's say that name = Jens, then i want it to return 99776612 that is the tlf number to Jens, and then the input of 'newNumber' will replace this number. i am new to python.
def change_number():
while True:
try:
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
datafile = open('telephonelist.txt')
if name in open('telephonelist.txt').read():
for line in datafile:
if line.strip().startswith(name):
line = line.replace(name,newNumber)
print('I found', name)
quit()
else:
print('I could not find',name+',','please try again!\n')
continue
except ValueError:
print('nn')
change_number()
This i telephonelist.txt
Kari 98654321
Liv 99776655
Ola 99112233
Anne 98554455
Jens 99776612
Per 97888776
Else 99455443
Jon 98122134
Dag 99655732
Siv 98787896
Load content, modify it, seek to beginning of the file, write the modified content again and then truncate the rest.
def change_number():
name = input('Name: ') #Enter name
newNumber = input('New number: ') # Wanted new number
with open('telephonelist.txt', 'r+') as file:
data = file.read().splitlines()
data = [line if not line.split()[0] == name else f"{name} {newNumber}" for line in data]
file.seek(0)
file.write("\n".join(data))
file.truncate()
change_number()

readline is reading more than one line

so the code is pretty simple, if the user doesn't enter a viable file then the program shuts down, however when I'm trying to move the opened files from the open_file() function to the main function, then use it in a read_file() function. However it's printing out more than just the first line when i go to print it to test it... im just trying to grab the 4th word separated by commas on the 2nd line.
#opens the file for data
def open_file():
input_file = input("Enter a food crop file: ")
try:
f1 = open(input_file,"r")
next(f1)
except FileNotFoundError:
print("File not found; terminating program.")
return False,False
input_file2 = input("Enter a non-food crop file: ")
try:
f2 = open(input_file2,"r")
next(f2)
except FileNotFoundError:
print("File not found; terminating program.")
return False,False
return f1,f2
def read_files(f1,f2):
line1 = f1.readline()
list_line1 = line1.replace(',','').split()
product1 = list_line1[3]
line2 = f2.readline()
list_line2 = line2.replace(',','').split()
product2 = list_line2[3]
print(product1,product2)
return product1,product2
#main fucntion, will call all other functions
def main():
f1,f2 = open_food_file()
while f1 != False:
product1,product2 = read_files(f1,f2)
#launches code
main()
It should look like this
Enter a food crop file: file_name.csv
Enter a non-food crop file: file_name.csv
product1 = 4th item in list for file1 here
product2 = 4th item in list for file2 here
it returns this, but then it errors out with
File "C:/COLLEGE/CSE/CSE 231/Code/redo.py", line 28, in read_files
product1 = list_line1[3]
IndexError: list index out of range

Using the split() or find() function in python

Am writing a program that opens a file and looks for line which are like this:
X-DSPAM-Confidence: 0.8475.
I want to use the split and find function to extract these lines and put it in a variable. This is the code I have written:
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"): continue
Please, Please I am now beginning in python so please give me something simple which I can understand to help me later on. Please, Please.
I think the only wrong part is not in if :
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
lines = []
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
lines.append(line)
First receive the input with raw_input()
fname = raw_input("Enter file name: ")
Then check if the input string is empty:
if not fname:
fname = 'mbox-short.txt'
Then, open the file and read it line by line:
lines = []
with open(fname, 'r') as f:
for line in f.readlines():
if line.startswith("X-DSPAM-Confidence:"):
lines.append(line)
The with open() as file statement just ensures that the file object gets closed when you don't need it anymore. (file.close() is called automatically upon exiting out of the with clause)
I know where this one is coming from as I've done it myself some time ago. As far as I remember you need to calculate the average :)
fname = raw_input("Enter file name: ")
fh = open(fname)
count = 0
sum = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count = count + 1
pos = line.find(' ')
sum = sum + float(line[pos:])
average = sum/count
You're very close, you just need to add a statement below the continue adding the line to a list.
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
fh = open(fname,'r')
total = 0
lines = []
for line in fh:
if not line.startswith("X-DSPAM-Confidence:"):
continue
lines.append(line) # will only execute if the continue is not executed
fh.close()
You should also look at the with keyword for opening files - it's much safer and easier. You would use it like this (I also swapped the logic of your if - saves you a line and a needless continue):
fname = raw_input("Enter file name: ")
if len(fname) == 0:
fname = 'mbox-short.txt'
total = 0
good_lines = []
with open(fname,'r') as fh:
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
good_lines.append(line)
If you just want the values, you can do a list comprehension with the good_lines list like this:
values = [ l.split()[1] for l in good_lines ]

Copy 'N' lines from one file to another in python?

Essentially what I am attempting to do is read 'n' number of lines from a file and then write them to a separate file. This program essentially should take a file that has 100 lines and separate that file into 50 separate files.
def main():
from itertools import islice
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ")
file1 = open(userfile, "r+")
#print "Name: ", file1.name
#print "Closed or not", file1.closed
#print "Opening mode: ", file1.mode
#print "Softspace flag: ", file1.softspace
jcardtop = file1.read(221);
#print jcardtop
n = 2
count = 0
while True:
next_n_lines = list(islice(file1,n))
print next_n_lines
count = count + 1
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(jcardtop))
fileout.write(str(next_n_lines))
fileout.close()
break
if not next_n_lines:
break
I do have the file printing as well to show what is in the variable next_n_lines.
*['\n', "randomtext' more junk here\n"]
I would like it instead to look like
randomtext' more junk here
Is this a limitatoin of the islice function? Or am I missing a portion of the syntax?
Thanks for your time!
Where you call str() or print, you want to ''.join(next_n_lines) instead:
print ''.join(next_n_lines)
and
fileout.write(''.join(next_n_lines))
You can store the flattened string in a variable if you don't want to call join twice.
Did you mean something like this?
f = open(userfile,"r")
start = 4
n_lines = 100
for line in f.readlines()[start:(start + n_lines)]:
print line
#do stuff with line
or maybe this rough, yet effective code:
f = open(userfile,"r")
start = 4
end = start + 100
count = start
while count != end:
for line in f.readlines()[count:(count + 2)]:
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(line))
fileout.close()
count = count + 2

Categories