problem with python list - python

Hi im trying to create a list adding to it via a for loop reading line by line from a txt file. Im getting a syntax error on the list but am unsure about how to fix the problem ???
import re
file = open("text.txt","r")
text = file.readlines()
file.close()
line_count=0
for line in text:
User_Input_list[] += [] + line.split()
line_count += 1
the problem seems to be on the second last line with the declaration of the list

Do it like this:
input = []
line_count = 0
with open("text.txt","r") as file:
for line in file:
input.extend(line.split())
line_count += 1

Why not
UserInputList += line.split()?

If you want each line in the file to be a separate element in the list, here's a simpler way to do it:
import re
file = open("text.txt","r")
text = file.readlines()
file.close()
line_count=0
line_list = []
for line in text:
line_list.append(line)
line_count += 1
Or using list comprehension:
import re
file = open("text.txt","r")
text = file.readlines()
file.close()
line_list = []
[line_list.append(a_line) for a_line in text]
line_count = len(line_list)

Related

How Can I read a string from a txt file line by line and run it with a function?

I have a txt file named a.txt. In this file a has a string per line. I want to append these strings line by line to the keyword = {} dict and run my double_letter function for each line of string. How can I do it?
my double_letter function:
keyword = {}
def double_letter():
print("\nDouble Letter:\n")
idx = random.randint(0, len(keyword) - 1)
keyword = keyword[:idx] + keyword[idx] + keyword[idx:]
print(keyword)
You can open, read and print the contents of a txt file as follows:
f = open("a.txt", "r")
for line in f:
print(line)
You can add in your function for each run through the for loop, i.e. calling it during each line of the text:
f = open("a.txt", "r")
for line in f:
print(line)
double_letter()
IIUC
Code
import random
def double_letter(line):
'''
Repeats random letter in line
'''
if line:
idx = random.randint(0, len(line) - 1)
return line[:idx] + line[idx] + line[idx:]
else:
return line # does nothing with blank lines
with open("a.txt", "r") as f: # with preferred with open file
keyword = {} # setup results dictionary
for line in f:
line = line.rstrip() # remove the '\n' at the end of each line
keyword[line] = double_letter(line) # add line with it's repeat to dictionary
print(keyword)
File a.txt
Welcome
To
Stackoverflow
Output
{'Welcome': 'Welcomee', 'To': 'Too', 'Stackoverflow': 'Stackoverfloow'}

python text file parse and print

I have a text file with 300 lines.
I am looking for a word "ABC" in each line
If this word is found i want to print the line before it was found and then the next X lines.
This is the code i have so far but i don't know how to print based on given problem statement.
path = ('C:\\Users\\40081\\PycharmProjects\\datalog_parsing')
count2=1
count1=1
num_lines = open('BBCnt123.txt').read().count('\n')
print (num_lines)
count2=count1
while count2<=num_lines:
file_name = open("BBCnt123.txt", 'r+')
f= open('BBCnt1234' + '.txt', 'w+')
for line_no, line in enumerate (file_name):
line=f.readlines()
if "BBCnt" in line:
f.writelines((line[count2-1]) )
count2= count2+1
file_name.close()
f.close()
with open("file.txt","r") as f:
lines=f.readlines()
[print(lines[c-1]+lines[c:c+X]) for c,e in enumerate(lines) if "ABC" in e]
Try this list comprehension

Replace string in line without adding new line?

I want to replace string in a line which contain patternB, something like this:
from:
some lines
line contain patternA
some lines
line contain patternB
more lines
to:
some lines
line contain patternA
some lines
line contain patternB xx oo
more lines
I have code like this:
inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []
for line in inputfile:
dummy += line
if line.find("patternA") != -1:
for line in inputfile:
dummy += line
if line.find("patternB") != -1:
item = line.split()
dummy += item[0] + " xx " + item[-1] + "\n"
break
outputfile.write(dummy)
It do not replace the line contain "patternB" as expected, but add an new line below it like :
some lines
line contain patternA
some lines
line contain patternB
line contain patternB xx oo
more lines
What can I do with my code?
Of course it is, since you append line to dummy in the beginning of the for loop and then the modified version again in the "if" statement. Also why check for Pattern A if you treat is as you treat everything else?
inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []
for line in inputfile:
if line.find("patternB") != -1:
item = line.split()
dummy += item[0] + " xx " + item[-1] + "\n"
else:
dummy += line
outputfile.write(dummy)
The simplest will be:
1. Read all File into string
2. Call string.replace
3. Dump string to file
If you want to keep line by line iterator
(for a big file)
for line in inputfile:
if line.find("patternB") != -1:
dummy = line.replace('patternB', 'patternB xx oo')
outputfile.write(dummy)
else:
outputfile.write(line)
This is slower than other responses, but enables big file processing.
This should work
import os
def replace():
f1 = open("d:\myfile.abc","r")
f2 = open("d:\myfile_renew.abc","w")
ow = raw_input("Enter word you wish to replace:")
nw = raw_input("Enter new word:")
for line in f1:
templ = line.split()
for i in templ:
if i==ow:
f2.write(nw)
else:
f2.write(i)
f2.write('\n')
f1.close()
f2.close()
os.remove("d:\myfile.abc")
os.rename("d:\myfile_renew.abc","d:\myfile.abc")
replace()
You can use str.replace:
s = '''some lines
line contain patternA
some lines
line contain patternB
more lines'''
print(s.replace('patternB', 'patternB xx oo'))

Writing before specific line python

i have this piece of code:
asm = open(infile)
asmw = open(outfile, "w")
shutil.copyfile(infile, outfile)
for x in range(0, 8):
xorreg.append("xor " + reg[x] + ", " + reg[x])
for line in asm:
if any(s in line for s in xorreg):
found += line.count(xorreg[x])
print line
i want to write some text lines in the file right before "line" (the one printed)
how can i do that?
Thanks
This script appends to every lien containing the string Gandalf a new string The greatest wizard of all times was:
# show what's in the file
with open("some_file.txt", 'r') as f:
print f.read()
new_content = []
with open("some_file.txt", "r") as asmr:
for line in asmr.readlines():
if "Gandalf" in line:
# we have a match,we want something but we before that...
new_content += "The greatest wizard of all times was:"
new_content += line
# write the file with the new content
with open("some_file.txt", "w") as asmw:
asmw.writelines(new_content)
# show what's in the file now
with open("some_file.txt", 'r') as f:
print f.read()

Why aren't the lists populating in this code?

I wrote this code for class and cannot figure out why my lists are not populating with any values. I've tried using a debugger and still can't figure out why it won't work. Any ideas? Also... I know for loops would have made more sense, but I needed to use while loops for the assignment.
__author__ = 'Ethan'
#This program reads in a file from the user which contains lines of
def mileage():
filename = input("Please enter the file name: ")
file = open(filename,"r")
line_list = []
num_lines = sum(1 for line in file)
line_counter = 0
while line_counter <= num_lines:
line = file.readline()
line_items = line.split()
line_list.append(line_items)
line_counter += 1
current_index_pos = 0
while current_index_pos <= num_lines:
current_item = line_list[current_index_pos]
print("Leg",current_index_pos + 1,"---", current_item[0]/current_item[1],"miles/gallon")
current_index_pos += 1
mileage()
This reads to the end of the file
num_lines = sum(1 for line in file)
so there are no lines left to read when you get here
line = file.readline()
Better to structure the code like this
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
line_items = line.split()
line_list.append(line_items)
# after the loop line_counter has counted the lines
or even (if you don't need line_counter)
with open(filename, "r") as fin:
line_list = [line.split() for line in fin]
More advanced would be to use a generator expression or do everything in a single loop to avoid needing to read the whole file into memory at once
def mileage():
filename = input("Please enter the file name: ")
with open(filename, "r") as fin:
for line_counter, line in enumerate(fin):
current_item = line.split()
print("Leg",line_counter + 1,"---", float(current_item[0])/float(current_item[1]),"miles/gallon")

Categories

Resources