Hi, I am a total noob...

I'm looking for a way to search a directory for config files and search each file for an entry that includes '1-' (bug apparently prepends this randomly) and delete that pesky 1- and save the file (on ubuntu).

Any help or suggestions would be greatly appreciated!

Here is an example how to find all the files with extension .ini in a given folder and add them to a list ...

# find all the .ini files in a folder
import os

print "add all the .ini in a folder to a list:"
folder = 'C:/Windows/'
file_list = []
for fname in os.listdir(folder):
  if fname.endswith('.ini'):
    file_list.append(fname)

# show the list
print(file_list)

Simpler yet ...

import os
import glob

os.chdir('C:/Windows/')
file_list = glob.glob('*.ini')
print(file_list)

Looks like using module glob is pretty cool!

This will give a sorted file list:

import os
import glob

os.chdir('C:/Windows/')
file_list = glob.glob('*.ini')
# sort case independent
print( sorted(file_list, key=str.lower) )

Works with IronPython 2.6 too.

Hi, I am a total noob...

I'm looking for a way to search a directory for config files and search each file for an entry that includes '1-' (bug apparently prepends this randomly) and delete that pesky 1- and save the file (on ubuntu).

Any help or suggestions would be greatly appreciated!

Is that pesky 1- at the beginning of a line?

Lardmeister

Yes, it is at the beginning of the line

Lardmeister

Yes, it is at the beginning of the line

thank you both for your help!! I really appreciate variations and multiple suggestions as they help me understand python better when I compare them. Thanks again!

A leading 1- will be easy to remove with slicing ...

# create faulty test data
data = """\
[Configuration]
1-Query Crash=1
Root Dir=C:\Program Files\Juno
[Communications]
Connect Method=1
[Crash Recovery]
1-TAPI=0
[Juno Clickthrough Config]
Preferred Modem=Agere Systems AC'99 Modem
1-Preferred Modem Id=0"""

print(data)  # test
print('-'*30)

# write test file
fname = "juno.ini"
fout = open(fname, "w")
fout.write(data)
fout.close()

# read the file line by line
new_data = ""
for line in open(fname, "r"):
    if line.startswith("1-"):
        # slice off the 2 leading characters
        line = line[2:]
    new_data += line

print(new_data)  # test

# write corrected test file
# overwrite old filename or use a new file name
fout = open(fname, "w")
fout.write(new_data)
fout.close()

Fantastic, thank you!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.