Reputation: 69
So basically I have .txt files in this sort of form
0 45 56 67 89
1 45 56 33 21
Some .txt files might also be blank. Some may contain one or more lines. Now I want to replace all the 1 in the first character of lines to 0. Everything else remains same. So the above .txt example should look like
0 45 56 67 89
0 45 56 33 21
I tried two ways One way was :
import glob
import os
source="path of my folder/"
for filename in glob.glob(os.path.join(source, '*.txt')):
with open(os.path.join(os.getcwd(), filename), "r+") as f:
lines = f.readlines()
for filename in glob.glob(os.path.join(source, '*.txt')):
with open(os.path.join(os.getcwd(), filename), "w+") as f:
for line in lines:
if line[0]=='1':
line[0].replace('1','0')
But this just removes all lines, regardless of whether it starts with 0 or 1
I have tried this:
source="path/ of my folder which has the files/"
for root, dirs, filenames in os.walk(source):
for f in filenames:
this_file = open(os.path.join(source, f), "r")
this_files_data = this_file.readlines()
this_file.close()
# rewrite the file with all line except the one you don't want
this_file = open(os.path.join(source, f), "w")
for line in this_files_data:
if line[0] in "1":
line[0].replace("0","1")
this_file.write(line)
this_file.close()
But this just removes all lines starting with 0 and keeps the ones with 1.
Upvotes: 1
Views: 823
Reputation: 781096
You should use just one loop. Read each file, make the changes you want, then rewrite the file.
You can use a regular expression to replace 1
at the start of each line.
import re
import glob
import os
for filename in glob.glob(os.path.join(source, '*.txt')):
with open(filename, "r") as f:
contents = f.read()
contents = re.sub(r'^1', '0', contents, flags = re.MULTILINE)
with open(filename, "w") as f:
f.write(contents)
You shouldn't use os.path.join(getcwd(), filename)
. The files are in the source
directory, not the current directory, and glob.glob()
returns those pathnames.
Upvotes: 1