I’m trying to remove all (non-space) whitespace characters from a file and replace all spaces with commas. Here is my current code:
def file_get_contents(filename):
with open(filename) as f:
return f.read()
content = file_get_contents('file.txt')
content = content.split
content = str(content).replace(' ',',')
with open ('file.txt', 'w') as f:
f.write(content)
when this is run, it replaces the contents of the file with:
<built-in,method,split,of,str,object,at,0x100894200>
The main issue you have is that you’re assigning the method
content.splitto content, rather than calling it and assigning its return value. If you print outcontentafter that assignment, it will be:<built-in method split of str object at 0x100894200>which is not what you want. Fix it by adding parentheses, to make it a call of the method, rather than just a reference to it:I think you might still have an issue after fixing that through.
str.splitreturns a list, which you’re then tuning back into a string usingstr(before trying to substitute commas for spaces). That’s going to give you square brackets and quotation marks, which you probably don’t want, and you’ll get a bunch of extra commas. Instead, I suggest using thestr.joinmethod like this:I’m not exactly sure if this is what you want though. Using
splitis going to replace all the newlines in the file, so you’re going to end up with a single line with many, many words separated by commas.