2

Okay so I'm having some troubles. I have a file with a few keywords in there. I have another file for the output.

I am trying to read each line from the first file, add a string at the end and the output to the last file.

Here's what I currently have:

def add(x, extend, file):
  extend = Extl
  file = open(file, "a")

  for i in extend:
    out = x + i + " + roy"

    file.write(out + "\n")
  file.close()

print("Starting...")

Extl = ['c', 's', 'aa', 'aqe','tdd', 'lap', 'tre', 'bgh', 'r' ]

Keys = []
Reader = open("Keywords.txt", "r")
for line in Reader:
  Keys.append(line)

S = 0  
while S < len(Keys):  
  xc = Keys[S]
  files = "File.txt"
  add(xc, Extl, files)
  S += 1

However when I receive the output, I get something like this:

Keypeo
c + roy
Keypeo
s + roy
Keypeo
aa + roy
Keypeo
aqe + roy
Keypeo
tdd + roy
Keypeo
lap + roy
Keypeo
tre + roy
Keypeo
bgh + roy
Keypeo
r + roy
Aewqc + roy
Aewqs + roy
Aewqaa + roy
Aewqaqe + roy
Aewqtdd + roy
Aewqlap + roy
Aewqtre + roy
Aewqbgh + roy
Aewqr + roy

It's not adding the keywords correctly, only the last few are fine.

Help would be much appreciated.

ProTechXS
  • 57
  • 1
  • 7

3 Answers3

1

Since it's not handy to link,

Reader = open("Keywords.txt", "r")
for line in Reader:
    Keys.append(line)

Can you try to change this to

Reader = open("Keywords.txt", "r")
for line in Reader:
    line = line.rstrip('\n')
    Keys.append(line)
Preatorian
  • 11
  • 3
0

Your file has new line characters at the end of some lines. This causes line breaks in between the concatenated text in the out variable. Before appending it into keys, strip off the new line characters. There are functions that directly give you a list by reading a file. Python Docs are an amazing source for finding such functions.

Keys = []
Reader = open("Keywords.txt", "r")
for line in Reader:
  Keys.append(line.rstrip('\n'))
AstroMax
  • 112
  • 9
0

I'm still not sure what you want because you didn't comment your code and you didn't post the specific results that you're looking for. If you want people to help you, you should always do that. So based on the available information this is what I came up with. My code works in Python 2.7.x. On a side note when you use with open() the opened file automatically gets closed when it's no longer needed.

#!python2

# adds an extension and ' + roy' to a key
def add(Keys, Ext1):
    # write results to a string
    out = ''

    for i in Keys:
        for j in Ext1:
            out += i + j + " + roy\n"

    # write string to file
    with open ('file.txt', 'w') as wf:
        wf.write(out)

    print 'Done!'

Keys = []
Extl = ['c', 's', 'aa', 'aqe', 'tdd', 'lap', 'tre', 'bgh', 'r' ]

print("Starting...")

# load keywords to 'Keys' list
with open('Keywords.txt', 'r') as fp:
    for line in fp:
        Keys.append(line.rstrip())

add(Keys, Extl)
Michael Swartz
  • 858
  • 2
  • 15
  • 27