I want to save in a new txt file a copy of another txt in Python

Asked

Viewed 931 times

0

arq = open("/Users/DIGITAL/Desktop/Python/novo.txt", "w")
arq.write(palavras)
arq.close()

I’m using this code, but it only accepts string.

  • Can you elaborate on what you want to do? What palavras? What’s the other file? Do you want to copy an entire file to another one? If so, why not just copy the file instead of reading one and write to another?

  • Words is what I am using to save this new ordination. I want to save in the new file the sort after applying quicksort with open('/Users/DIGITAL/Desktop/Python/test.txt') as f: words = Counter( f.read(). split())

1 answer

1


You can do something like this:

with open('test.txt', 'r') as arquivo_existente, open('novo_arquivo.txt', 
'w') as novo_arquivo:
    for linha in arquivo_existente.readlines():
        novo_arquivo.write(linha)

When executing the above code, the contents of the arquivo_existente.txt will be copied to the file novo_arquivo.txt

  • 1

    Tip: You can use both expressions starting from version 2.7 with in one single: with open(...) as a1, open(...) as a2, and read the entire content with read() instead of line by line with readlines().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.