'Replace space with underscore using python

I need some help, I have a a txt file with spaces between words, I want to replace the space with underscore.

fileHandler = open('nog_rename_update.txt')
for eachline in fileHandler:
    new_name = fileHandler.replace("      ","_")
print(new_name)

That's my code but it keeps throwing error messages

new_name = fileHandler.replace(" ","_") AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

example files that I want to remove space and add underscore



Solution 1:[1]

Try out this

fileHandler = open('nog_rename_update.txt').read()
new_name = fileHandler.replace(" ", "_")
print(new_name)

Solution 2:[2]

f = open("test.txt", "r") 
text=f.read() 
f.close() 
f=open("testfile.txt", "w+") 
text2='' 
if ' ' in text: 
    text2 = text.replace(' ' , '_') 
    print(text2) 
    f.write(text2) 
f.close()

Solution 3:[3]

Here's a generic approach that should work for you:

teststring = 'hello world     this is just a   test. don\'t mind me 123.'

# replace multiple spaces with one space
while '  ' in teststring:
    teststring = teststring.replace('  ', ' ')

# replace space with underscore (_)
teststring = teststring.replace(' ', '_')

print(teststring)
assert teststring == "hello_world_this_is_just_a_test._don't_mind_me_123."  # True

Using a file example:

fname = 'mah_file.txt'
with open(fname) as in_file:
    contents = in_file.read()
    while '  ' in contents:
        contents = contents.replace('  ', ' ')
# write updated contents back to file
with open(fname, 'w') as out_file:
    out_file.write(contents.replace(' ', '_'))

Solution 4:[4]

Here is another, less verbose solution. Simply use re.sub:

import re

file_name = r"D:\projects\playground\python\data\test.txt"

with open(file_name, "r") as file:
    for line in file:
        print(re.sub("( )+", "_", line), end="")

And if you want to replace the spaces in your text file:

import re

file_name = r"D:\projects\playground\python\data\test.txt"

lines = []

with open(file_name, "r") as file:
    lines = [
        re.sub("( )+", "_", line) for line in file.readlines()
    ]

with open(file_name, "w") as file:
    file.writelines(lines)

Or use fileinput:

import re
import fileinput

file_name = r"D:\projects\playground\python\data\test.txt"

with fileinput.FileInput(file_name, inplace=True, backup=".bak") as file:
    for line in file:
        print(re.sub("( )+", "_", line), end="")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Code Clickers
Solution 2
Solution 3
Solution 4