TXT File Manipulation using Python

Asked

Viewed 952 times

1

Let’s say I have one arquivo.txt which is separating the information only by the comma, for example,

X,Y,Z,W         
1,2,3,4

How do I modify such a file and save it so that it is a table without the presence of these commas (see the following illustration)?

X Y Z W         
1 2 3 4

1 answer

3

Come on, the first step is to manipulate the TXT file. For this, take a look at this link: http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

With this, the logic for implementation is to follow the following steps:

  1. Read the file lines;
  2. Replace the characters , (viper) by (blank space) and store them in a variable;
  3. Write the text stored in the variable in the same file.

Implementing the logic:

fileRead = open("arquivo.txt","r")

textoNovoArquivo = ''
for line in fileRead:
    textoNovoArquivo += line.replace(","," ")

fileRead.close()

fileWrite = open("/home/enio/python/arquivo.txt","w")

fileWrite.write(textoNovoArquivo)

fileWrite.close()

I hope I’ve helped. :)

  • Dear Enio Costa, your code worked. Thank you very much for your willingness. I hope to reach a level I can reciprocate by helping other people with their doubts. A strong hug.

  • 1

    This response uses techniques that are not recommended for large files: it loads the entire file data into memory and uses string concatenation for this. In this case it is recommended to read the data block by block (and not line by line) and write them to a secondary or temporary file as the data is read.

Browser other questions tagged

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