How can I save the changes for all text files in a directory?
My first aim was to replace all commas in all text files in a directory with space. (To work on them easily. I have 100 text files.)
I first took all the data as string, then applied the code below. It works. However, I am bit lack of knowledge about how to save those changes in all text files, in my actual folder.
Thank you for any help and recommendations.
The code;
from pathlib import Path
from os import listdir
from os.path import isfile, join
path = "/folder"
only_files = [f for f in listdir(path) if isfile(join(path, f))]
all_lines = []
for file_name in only_files:
file_path = Path(path) / file_name
with open(file_path, 'r') as f:
file_content = f.read()
file_content = file_content.replace(",", " ")
all_lines.append(file_content.splitlines())
print(file_content)
Solution 1:
You close the file and open it again for writing, then overwrite it:
from pathlib import Path
from os import listdir
from os.path import isfile, join
path = "/folder"
only_files = [f for f in listdir(path) if isfile(join(path, f))]
all_lines = []
for file_name in only_files:
file_path = Path(path) / file_name
with open(file_path, 'r') as f:
file_content = f.read()
# read https://stackoverflow.com/q/123198/7505395 for better
# ways to copy a file - this creates a backup of your current file
with open(file_path + ".bak", "w") as bak:
bak.write(file_content)
# this opens your file as new empty file and fills it
# with the replaced content
with open(file_path, "w") as f:
replaced_file_content = file_content.replace(",", " ")
f.write(replaced_file_content)
print(replaced_file_content)
Solution 2:
Basically what you want to do is overwrite the same file with modified data after reading its content. Here are two ways to go about it -
# read the file data
with open(file_path, 'r') as f:
data = f.read()
# modify the data here and generate newData
newData = data.replace(",", " ")
# write the file data, note w here for write
with open(file_path, 'w') as f:
f.write(newData)
Here's the second way, where we open the file only once. r+
mode is meant for opening a file for both reading + writing -
with open(file_path, 'r+') as f:
data = f.read() # read the file content
newData = data.replace(",", " ")
f.seek(0) # set the cursor to beginning of the file
f.write(newData) # overwrite the file with new data
f.truncate() # if newly written data is smaller than original data, truncate the file here