Copy a word right next to another

2

I'm starting with python and I'm trying to make a script that takes a txt file with a list of words vertically and copied the same word next to it this automatically, it would be something like that.

dictionary.txt:

casa123
perro454
gato783
raton12

and I want to get this:

casa123casa123
perro454perro454
gato783gato783
raton123raton123

What I have of the script is this, and I can not get it to show me what I want. I know it's simple but it's always hard to start. I hope you can help me and thank you.

#!/usr/bin/env python  

dic = open("/media/particion/dic.txt", "r+") for linea in dic:  
      dic2 = open("/media/particion/dic2.txt", "a")  
      s1 = linea + linea  
      dic2.write(s1)  
    
asked by Leandro Naranjo 23.08.2016 в 15:03
source

2 answers

2

It would be something like this:

#!/usr/bin/python

dic = open("/media/particion/dic.txt","r")
dic2 = open("/media/particion/dic2.txt", "w")
lineas= [linea+linea for linea in dic]

for texto in lineas:
    dic2.write("%s\n" % texto)

dic.close()
dic2.close()
    
answered by 23.08.2016 / 15:38
source
1

The answer of @David is very correct and I voted positive because it is a canonical response and the obvious one to solve the problem in question. Mine is just for fun and for showing a shorter solution using context managers available at Python from Python 2.5 (it's not something new) :

with open('/media/particion/dic.txt') as a, open('/media/particion/dic2.txt', 'w') as b:
    [b.write(line.replace('\n','')+line) for line in a]

A context manager in Python is nothing more than a object that is responsible for doing certain work for you to which you have to define the magic methods __enter__ and __exit__ so you know what to do.

Also, I used a list comprehension to write the data in the new file, other options could be used but I usually abuse the list comprehensions :-P

Update : As indicated by @ChemaCortes is a comment below, using a list comprehension you store a lot of information in memory that may not be relevant and you could use generators and

answered by 23.08.2016 в 16:27