I have a piece of code to make some changes in a file in Python. I wish to perform that action on multiple files of a folder. I wrote the following code to do that:
import re import os files = os.listdir("/home/intucell/tarfiles") for file in files: fp = open (file, 'r') for line in fp: print(line.replace ('4.0.0', '5.0.0')) f.close()
I want the code to run for multiple files in a folder called tarfiles. The names of these files have to be read from the listing of that folder. But, Linux does not read filenames containing spaces. I have about 100 files containing spaces in their names. How do I go about it?
Assuming that you have the list of files filelist
you want to work on, you can simply use:
import re
for filename in filelist:
fp = open (filename, 'r')
for line in fp: print(line.replace (' 4.0.0 ', ' 5.0.0 '))
print(re.sub(r'\b4.0.0[^.]', '5.0.0 ', line))`
Or do you need to look for the files in the folder?
You can use a for loop for this one. Eg
import os
item_list = next(os.walk(your_directory_path))[1]
for i in item_list:
fp = open (str(i), 'r')
for line in fp: print(line.replace (' 4.0.0 ', ' 5.0.0 '))
print(re.sub(r'\b4.0.0[^.]', '5.0.0 ', line))
I hope that will help
you can use os.listdir, suppose the multiple files you want to change are in folder which is stored in the path variable, then:
files = os.listdir(path)
for _file in files:
fp = open (_file, 'r')
for line in fp:
print(line.replace (' 4.0.0 ', ' 5.0.0 '))
print(re.sub(r'\b4.0.0[^.]', '5.0.0 ', line))
EDIT: also don't forget to import os
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.