-4

I am actually trying to remove or rename files name which contains question mark in python.

Does anyone would have some guidance or experience to share?

my files are like this:

??test.txt
?test21.txt
test??1.txt

the result that I am trying to get is:

test.txt
test21.txt
test1.txt

thank you for your help. AL

Below the code which I have attempted using the suggestion below:

#!/usr/bin/python
import sys, os, glob
for iFiles in glob.glob('*.txt'):
    print (iFiles)
    os.rename(iFiles, iFiles.replace("?",''))
user2335924
  • 57
  • 1
  • 9
  • 2
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ] and [ask]. – MooingRawr Sep 27 '17 at 13:44
  • 1
    `os.rename(f,f.replace("?",""))` – Jean-François Fabre Sep 27 '17 at 13:45
  • Possible duplicate of [Remove specific characters from a string in python](https://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) – mbrig Sep 27 '17 at 13:47
  • I'd point you to [os.rename](https://docs.python.org/3.6/library/os.html#os.rename) and [this question.](https://stackoverflow.com/questions/38071397/python-3-5-1-change-file-name) – Dan Sep 27 '17 at 13:58
  • Are you trying to delete a file on a system or rename a file on a sytem or just remove ? from a string? – iNoob Oct 27 '17 at 11:50

1 Answers1

0

This should do what you require.

import os
import sys
import argparse

parser = argparse.ArgumentParser(description='Rename files by replacing all instances of a character from filename')
parser.add_argument('--dir', help='Target DIR containing files to rename', required=True)
parser.add_argument('--value', help='Value to search for an replace', required=True)
args = vars(parser.parse_args())


def rename(target_dir, rep_value):
    try:
        for root, dirs, files in os.walk(target_dir):
            for filename in files:
                if rep_value in filename:
                    filename_new = str(filename).replace(rep_value, '')
                    os.rename(os.path.join(root, filename), os.path.join(root, filename_new))
                    print '{} renamed to {}'.format(filename, os.path.join(root, filename_new))
    except Exception,e:
        print e


target_dir = args['dir']
rep_value = args['value']
rename(target_dir, rep_value)

Example usage:

rename.py --dir /root/Python/ --value ?

Output

?test.txt renamed to /root/Python/test.txt
?test21.txt renamed to /root/Python/test21.txt
test1?.txt renamed to /root/Python/test1.txt
iNoob
  • 1,375
  • 3
  • 19
  • 47