[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Changing strings in files

Manfred Lotz <ml_news at> writes:

> I have a situation where in a directory tree I want to change a certain
> string in all files where that string occurs.
> My idea was to do
> - os.scandir and for each file
>    - check if a file is a text file
>    - if it is not a text file skip that file
>    - change the string as often as it occurs in that file
> What is the best way to check if a file is a text file? In a script I
> could use the `file` command which is not ideal as I have to grep the
> result. In Perl I could do  -T file.
> How to do best in Python?

If you are on Linux and more interested in the result than the
programming exercise, I would suggest the following non-Python solution:

   find . -type -f -exec sed -i 's/foo/bar/g' {} \;

Having said that, I would be interested to know what the most compact
way of doing the same thing in Python might be.



This signature is currently under construction.