I am having some trouble getting a part of my code to read a value from a text file which then can be converted to an integer and then modified by adding a user input value, then input the new value into the file. This is for a simple inventory program that keeps track of certain items.
Example:
User inputs 10 to be added to the number in the file. The number in the file is 231 so 10+231 = 241. 241 is the new number that is put in the file in place of the original number in the file. I have tried many different things and tried researching this topic, but no code I could come up with has worked. If it isn't apparent by now I am new to python. If anyone one can help it would be greatly appreciated!
the steps that you need to take are
Open the file in read mode: file = open("path/to/file", "r")
Read the file to a python string: file_str = file.read()
Convert the string to an integer: n = int(file_str)
Add 10 and convert num: num_str = str(n + 10)
Close the file: file.close()
Reopen the file in write mode: file = open("path/to/file", "w")
Write the num string to the file: file.write(num_str)
If your is
1 2 3 4 5 6
7 8 9 10 11 12
....
....
then,go searching line by line and find the line number and index of your number.
with open('data.txt') as f:
content = f.readlines()
for x in range(len(content)):
if '5' in content[x].split(' '):
lno = x
index = content[x].split(' ').index('5')
So,now you got the index.Add the user input to the number and save it into the file as you have the line number and index.
Related
have to write in python 2 txt.files one is input of numbers: writen in 2 lines 4-1 and 12-3 I have to make the subtraction and write the result to other txt.file
please help me I am very green to python, just started to learn it.
Thanks you all in advance
this is what I managed to write till now:
import calculator
with open ('./expresii.txt', 'r') as f:
line = f.readlines()
for l in line:
if l[1] == '-':
print(calculator.subtraction(int(l[0]), int(l[2])))
else:
print(calculator.addition(int(l[0]), int(l[2])))
with open ('./expresii.txt', 'r') as f2:
print(f2.read())
in first I get the subtraction of numbers
and from the second I get the numbers that must be subtrated
now how do I write toa new file 4-1=3 and 12-3=9 this must be the result
Here is a Python 2.7 Solution:
import re
# opens the input file in readmode
with open ('expresii.txt', 'r') as f:
# creates an iterable of the lines in the file
lines = f.readlines()
# create an empty array which will store the data to write to the output file
to_file = []
# loops through every line in the file
for l in lines:
# creates a list of ints of all the numbers in that line
nums = list(map(int, re.findall(r'\d+', l)))
# calculate the result by subtracting the two numbers
result = nums[0] - nums[1]
# append answer (e.g 4-1=3) to a list, that will later be written to a file
line = str(nums[0])+'-'+str(nums[1])+'='+str(result)+'\n'
to_file.append(line)
#open the output file in write mode
with open('output_file.txt', 'w') as f:
# write the to_file list to output_file.txt
f.writelines(to_file)
This solution finds all of the numbers, in each line of the file, and calculates the result when you subtract them. After it has done this for every line in the input file, it then writes this data to an output file.
I wish you well as you continue to learn Python :)
I have a text file that 10 numbers 0 to 10 written line by line(downward).
Such as;
2
4
5
1
7
6
9
0
2
4
So, how can I write those numbers in a list while reading?
sample of my code:
emptyList=[] # I need to push into "testnumbers.txt"
read = open('testnumbers.txt')
# use readline() to read the first line
line = read.readline()
# use the read line to read further.
# If the file is not empty keep reading one lineat a time, till the file is empty
while line:
# print line
print(line)
line = read.readline()
read.close()
After pushing numbers in list:
emptyList=[2,4,5,1,7,6,9,0,2,4]
print(emptyList)
I'm trying to get result like that:
[2,4,5,1,7,6,9,0,2,4]
You can use the list.append() method after you convert each line to an integer:
emptyList = []
while line:
print(line)
emptyList.append(int(line))
line = read.readline()
I have a txt file that reads as follows:
math,89
history,90
history,94
I am trying to split each line so I can convert the the numbers to integers and use the numbers to find the average grade. I am having issues with splitting the string at the ' , ' and storing the 2 parts I split into 2 different variables.
Here is the main part of the code that i think is the issue:
def main():
total = 0
count = 0
myfile = open('grades.txt','r')
for line in myfile:
array = line.split(",")
course = array[0]
amount = float(array[1])
total += amount
myfile.close()
Sorry forgot to add the error I am getting: ValueError: I/O operation on closed file
I have a file sized 15-16GB containing json objects seperated by new line (\n).
I am new to python and reading the file using the following code.
with open(filename,'rb') as file:
for data in file:
dosomething(data)
If while reading the reading ,my script fails after 5GB, how can I resume my read operation from the last read position and continue from there.
I am trying to do the same by using the file.tell() to get position and move the pointer using the seek() function.
Since this file contains json objects, after seek operation am getting the below error.
ValueError: No JSON object could be decoded
I am assuming that after seek operation the pointer is not getting proper json.
How can I solve this?. Is there any other way to read from last read position in python.
Use another file to store the current location:
cur_loc = open("location.txt", "w+")
cur_loc.write('0')
exception = False
i = 0
with open("test.txt","r") as f:
while(True):
i+=1
if exception:
cur_loc.seek(0)
pos = int(cur_loc.readline())
f.seek(pos)
exception = False
try:
read = f.readline()
print read,
if i==5:
print "Exception Happened while reading file!"
x = 1/0 #to make an exception
#remove above if block and do everything you want here.
if read == '':
break
except:
exception = True
cur_loc.seek(0)
cur_loc.write(str(f.tell()))
cur_loc.close()
Let assume we have the following text.txt as input file:
#contents of text.txt
1
2
3
4
5
6
7
8
9
10
When you run above program, you will have:
>>> ================================ RESTART ================================
>>>
1
2
3
4
5
Exception Happened while reading file!
6
7
8
9
10
>>>
You can use for i, line in enumerate(opened_file) to get the line numbers and store this variable. when your script fails you can display this variable to the user. You will then need to make an optional command line argument for this variable. if the variable is given your script needs to do opened_file.readline() for i in range(variable). this way you will get to the point where you left.
for i in range(passed_variable):
opened_file.readline()
So far I have this. I opened the data file, I was able to make a list from the data and print the data I needed from the list in 2 columns correctly. It shows up in python just fine. But when I try to write it to a txt file, it all shows up on 1 line. Not sure what to do so it's into 2 columns in the new text file.
# open file
data = open("BigCoCompanyData.dat", "r")
data.readline()
# skip header and print number of employees
n = eval(data.readline())
print(n)
# read in employee information
longest = 0
# save phone list in text file
phoneFile = open("PhoneList.txt", "w")
for i in range(n):
lineI = data.readline().split(",")
nameLength = len(lineI[1])+len(lineI[2])
if nameLength > longest:
longest = nameLength
longest = longest + 5
print((lineI[2].title()+", "+lineI[1].title()).ljust(longest) + ("("+lineI[-2][0:3]+")"+lineI[-2][3:6]+"-"+lineI[-2][6:10]).rjust(14))
phoneFile.write((lineI[2].title()+", "+lineI[1].title()).ljust(longest) + ("("+lineI[-2][0:3]+")"+lineI[-2][3:6]+"-"+lineI[-2][6:10]).rjust(14))
data.close()
# close the file
phoneFile.close()
phoneFile.write(...)simply writes the line you give it. Every time you give a line it appends it to the previous lines, unless you end your lines with \n.
phoneFile.write((lineI[2].title()+", "+lineI[1].title()).ljust(longest) +
("("+lineI[-2][0:3]+")"+lineI[-2][3:6]+"-"+lineI[-2][6:10]).rjust(14)+'\n')