My current code is:
file = open("quotes.txt", "r")
lines = file.readlines()
quote = 0
quoteList = [line.split()for line in open ("quotes.txt")]
print(quoteList)
lines = []
for l in lines:
lines.append(l.split(" "))
I am trying to open a file and have it read the paragraphs in it and split them up into individual items in a list. It is a file filled with quotes and they all go something like this:
No problem should ever have to be solved twice.
-- Eric S. Raymond, How to become a hacker
There's about a thousand lines of quotes in the file and I am wondering how to split them up and put them into a list where you can access individual quotes and print them at random.
Related
Bringing in a text file that is formatted like below:
hammer#9.95
saw#20.15
shovel#35.40
I need to bring it into python and format it so that it is in line with an existing snippet of code:
# display header line for items list
print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep = '' )
The goal is for the text file to be in line with existing headers like so:
Item Cost
hammer $9.95
saw $20.15
shovel $35.4
I can bring in the text file into Python and get replace the # sign with a $ sign:
file = open('Invoice.txt', 'r')
file_contents = file.read()
new_file_contents = file_contents.replace('#', '$')
Which gives me this output:
hammer$9.95
saw$20.15
shovel$35.40
but I'm having trouble with the formatting aspect. Any suggestions?
You can do something like this:
with open(file,'rt',encoding='utf-8') as infile:
for line in infile:
print("{:<6} {}".format(line.strip().split('#')[0],"$"+line.strip().split("#")[1]))
only problem is that it'll look ugly if you have a longer word than hammer. I suggest finding the largest word in your list first, then using that as the limiter for the {:<6}.
I have two text files with numbers that I want to do some very easy calculations on (for now). I though I would go with Python. I have two file readers for the two text files:
with open('one.txt', 'r') as one:
one_txt = one.readline()
print(one_txt)
with open('two.txt', 'r') as two:
two_txt = two.readline()
print(two_txt)
Now to the fun (and for me hard) part. I would like to loop trough all the numbers in the second text file and then subtract it with the second number in the first text file.
I have done this (extended the coded above):
with open('two.txt') as two_txt:
for line in two_txt:
print line;
I don't know how to proceed now, because I think that the second text file would need to be converted to string in order do make some parsing so I get the numbers I want. The text file (two.txt) looks like this:
Start,End
2432009028,2432009184,
2432065385,2432066027,
2432115011,2432115211,
2432165329,2432165433,
2432216134,2432216289,
2432266528,2432266667,
I want to loop trough this, ignore the Start,End (first line) and then once it loops only pick the first values before each comma, the result would be:
2432009028
2432065385
2432115011
2432165329
2432216134
2432266528
Which I would then subtract with the second value in one.txt (contains numbers only and no Strings what so ever) and print the result.
There are many ways to do string operations and I feel lost, for instance I don't know if the methods to read everything to memory are good or not.
Any examples on how to solve this problem would be very appreciated (I am open to different solutions)!
Edit: Forgot to point out, one.txt has values without any comma, like this:
102582
205335
350365
133565
Something like this
with open('one.txt', 'r') as one, open('two.txt', 'r') as two:
next(two) # skip first line in two.txt
for line_one, line_two in zip(one, two):
one_a = int(split(line_one, ",")[0])
two_b = int(split(line_two, " ")[1])
print(one_a - two_b)
Try this:
onearray = []
file = open("one.txt", "r")
for line in file:
onearray.append(int(line.replace("\n", "")))
file.close()
twoarray = []
file = open("two.txt", "r")
for line in file:
if line != "Start,End\n":
twoarray.append(int(line.split(",")[0]))
file.close()
for i in range(0, len(onearray)):
print(twoarray[i] - onearray[i])
It should do the job!
I am using python 3.4.2 and visual studio code i am a total newbie
I have been trying to search for the answer, but probably don't know enough to search for the right answers. I am trying to learn python and this is my learning tool. It is a redo of a program I wrote in basic in the early 80's on a TRASH32 where I couldn't access a data file and had to enter the data by hand.
I want to open a file that is a long string with the items (spaces, str, int)
separated with commas. (example:"EMD","20170820", 1, 1,,870,"D",,"N","BUN",") but about 450,000 charaters long. I am trying to make a list of strings separated at the commas so that I can call them up, list[0:6] returns 870, ect..
I have tried-
lines = tuple(open('filename','r')) # all in only one string.
print(list) # this showed whole file was read.
I tried-
with open('filename'): -this opens file as a list of strings, but only
list = line.split(',') the last third of the file is in the list.
print(list) # this showed whole file was read.
I tried-
with open('filename',('r'))as f: -this also opens the file as a list of
reader = csv.reader(f) strings, only the last third or so of the
list = list(reader) file is in the list.
print(list) # this showed whole file was read.
I guess my question is, what can I do with the 'with open(filename')code' to make the whole file accessible so that I can work with it? Below is a sample of my code and an example of the results. If that is not feasible, how can I convert a long string with values separated by commas into a list of strings
of the values.
import sys
import os
import csv
with open('c:/code/EMD0820.DRF'):
for line in open('c:/code/EMD0820.DRF'):
list = line.split(',')
#print(list) # this shows entire file came thru
str_list=str(list)
print (str_list[0:30]) # this prints out 29 characters 1a
#print(line[0:5]) # this prints "EMD" 1b
#print(list) # this prints lists but only from page 117 of 119 to the end. 1c
print (list[1:15]) # prints first 14 strings starting where print(line[0:5]) did. 1d
results
1a ['"EMD"', '"20170820"', '11',
1b "EMD"
1c ["EMD","20170820",11, 8,,1320,"D",,"C","BUN","Clm2500n2l",6000,............to end of file]
1d [,"20170820",11, 8,,1320,"D",,"C","BUN","Clm2500n2l",6000,2500,2500,66.86]
with open('/path/to/file') as f:
content = f.read().replace('\n', ',')
content_list = content.split(',')
print(content_list)
You need to read the file into an object in memory. Then you can call split().
Try:
with open('c:/code/EMD0820.DRF') as f:
read_file = f.read()
l = read_file.split(",")
I am using Python-3 and I am reading a text file which can have multiple paragraphs separated by '\n'. I want to split all those paragraphs into a separate list. There can be n number of paragraphs in the input file.
So this split and output list creation should happen dynamically thereby allowing me to view a particular paragraph by just entering the paragraph number as list[2] or list[3], etc....
So far I have tried the below process :
input = open("input.txt", "r") #Reading the input file
lines = input.readlines() #Creating a List with separate sentences
str = '' #Declaring a empty string
for i in range(len(lines)):
if len(lines[i]) > 2: #If the length of a line is < 2, It means it can be a new paragraph
str += lines[i]
This method will not store paragraphs into a new list (as I am not sure how to do it). It will just remove the line with '\n' and stores all the input lines into str variable. When I tried to display the contents of str, it is showing the output as words. But I need them as sentences.
And my code should store all the sentences until first occurence of '\n' into a separate list and so on.
Any ideas on this ?
UPDATE
I found a way to print all the lines that are present until '\n'. But when I try to store them into the list, it is getting stored as letters, not as whole sentences. Below is the code snippet for reference
input = open("input.txt", "r")
lines = input.readlines()
input_ = []
for i in range(len(lines)):
if len(lines[i]) <= 2:
for j in range(i):
input_.append(lines[j]) #This line is storing as letters.
even "input_ += lines" is storing as letters, Not as sentences.
Any idea how to modify this code to get the desired output ?
Don't forgot to do input.close(), or the file won't save.
Alternatively you can use with.
#Using "with" closes the file automatically, so you don't need to write file.close()
with open("input.txt","r") as file:
file_ = file.read().split("\n")
file_ is now a list with each paragraph as a separate item.
It's as simple as 2 lines.
My text.txt looks like this
abcd
xyzv
dead-hosts
-abcd.srini.com
-asdsfcd.srini.com
And I want to insert few lines after "dead-hosts" line, I made a script to add lines to file, there is extra space before last line, that's mandatory in my file, but post added new lines that space got removed, dont know how to maintain the space as it is.
Here is my script
Failvrlist = ['srini.com','srini1.com']
tmplst = []
with open(‘test.txt’,'r+') as fd:
for line in fd:
tmplst.append(line.strip())
pos = tmplst.index('dead-hosts:')
tmplst.insert(pos+1,"#extra comment ")
for i in range(len(Failvrlist)):
tmplst.insert(pos+2+i," - "+Failvrlist[i])
tmplst.insert(pos+len(Failvrlist)+2,"\n")
for i in xrange(len(tmplst)):
fd.write("%s\n" %(tmplst[i]))
output is as below
abcd
xyzv
dead-hosts
#extra comment
- srini.com
- srini1.com
- abcd.srini.com
- asdsfcd.srini.com
if you look at the last two lines the space got removed, please advise .
Points:
In you code , pos = tmplst.index('dead-hosts:'), you are trying to find dead-hosts:. However, input file you have given has only "dead hosts". No colon after dead-hosts, I am considering dead-hosts:
While reading file first time into list, use rstrip() instead of strip(). Using rstrip() will keep spaces at the start of line as it is.
Once you read file into list, code after that should be outside with block which is use to open and read file.
Actually, flow of code should be
Open file and read lines to list and close the file.
Modify list by inserting values at specific index.
Write the file again.
Code:
Failvrlist = ['srini.com','srini1.com']
tmplst = []
#Open file and read it
with open('result.txt','r+') as fd:
for line in fd:
tmplst.append(line.rstrip())
#Modify list
pos = tmplst.index('dead-hosts:')
tmplst.insert(pos+1,"#extra comment")
pos = tmplst.index('#extra comment')
a = 1
for i in Failvrlist:
to_add = " -" + i
tmplst.insert(pos+a,to_add)
a+=1
#Write to file
with open('result.txt','w') as fd:
for i in range(len(tmplst)):
fd.write("%s\n" %(tmplst[i]))
Content of result.txt:
abcd
xyzv
dead-hosts:
#extra comment
-srini.com
-srini1.com
-abcd.srini.com
-asdsfcd.srini.com