Home > Enterprise >  How to convert space separated file to tab delimited file in python?
How to convert space separated file to tab delimited file in python?

Time:12-05

I have two data files, viz., 'fin.dat' and 'shape.dat'. I want to format 'shape.dat' just the way the 'fin.dat' is written with Python. The files can be found here https://easyupload.io/m/h94wd3. The snippets of the data structures are given here fin.dat,shape.dat. Please help me doing that.

CodePudding user response:

To convert a space-separated file to a tab-delimited file in Python, you can use the replace() method to replace all occurrences of spaces with tabs. Here's an example:

# Open the file in read mode
with open('input.txt', 'r') as input_file:
    # Read the file content
    content = input_file.read()

# Replace all occurrences of space with tab
content = content.replace(' ', '\t')

# Open the file in write mode
with open('output.txt', 'w') as output_file:
    # Write the modified content to the file
    output_file.write(content)

In this example, the input.txt file is read and its content is stored in the content variable. Then, all occurrences of space are replaced with tab using the replace() method. Finally, the modified content is written back to the output.txt file.

You can modify this code to work with your specific requirements. For example, you can use different delimiters, or you can process the file line by line instead of reading and writing the entire content in one go.

CodePudding user response:

with open('shape.dat') as fin, open('new.dat', 'w') as fout:
#to have data in separate columns from a single column
for line in fin:
    fout.write(line.replace('\t', ','))

Hi Hirak try the code above. It worked in my system. Here is output after operation

  • Related