In: Computer Science
Code in python
Hello I want a program to read only the price of each line in a txt file in python. The price is present right after the 2nd comma within the txt file. The output that I want is also printed at the bottom.
Inside the txt file:
2019-08-01 00:08:39,BTC/USD,10128.08
2019-08-01 00:08:21,BTC/USD,10117.54
2019-08-01 00:08:20,BTC/USD,10120.51
2019-08-01 00:08:19,BTC/USD,10118.13
2019-08-01 00:08:18,BTC/USD,10120.74
Python file output:
Price 1: 10128.08
Price 2: 10117.54
Price 3: 10120.51
Price 4: 10118.13
Price 5: 10120.74
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments(read them for better understanding).
Images of the Code:
File:- I have named file as text.txt. Please place the file where the python file is placed.
Note: If the below code is missing indentation please refer code Images
Typed Code:
#getting file name as input from the user
file_name = input("Enter file name: ")
#opening the file
file = open(file_name)
#reading file content
file_content = file.read()
#splitting lines of the file using '\n'(new line character)
lines = file_content.split('\n')
#closing file
file.close()
#opening file again to append prices
file = open(file_name, "a")
#for loop will iterate len(lines) times
for i in range(len(lines)):
#splitting lines using ',' comma
line = lines[i].split(',')
#if len(line) < 3
if len(line) < 3 :
#break
break
#storing line[2] to content
content = '\nPrice {}: {}'.format(i+1,line[2])
#writing the content to file
file.write(content)
#writing new line in file
file.write('\n')
#printing output added successfully to screen
print("Output added to the file '{}'
Successfully.".format(file_name))
#closing file
file.close()
#code ended here
Output:
Prices printed at the bottom. Inside the txt file(text.txt) :-
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!