Allen
Allen

Reputation: 149

How can i adjust my code to remove print desired values only

My current code:

def write_from_dict(users_folder):
    for key, value in value_dict.items():  # iterate over the dict
        file_path = os.path.join(users_folder, key + '.txt')
        with open(file_path, 'w') as f:       # open the file for writing
            for line in value:                # iterate over the lists

                f.write('{}\n'.format(line))

My current output:

['4802', '156', '4770', '141']
['4895', '157', '4810', '141']
['4923', '156', '4903', '145']

My desired output:

4802,156,4770,141
4895,157,4810,141
4923,156,4903,145

so basically i want the spaces '' and [] removed.

Upvotes: 2

Views: 40

Answers (2)

Joe Iddon
Joe Iddon

Reputation: 20414

At the moment, line is a list of ints, we need to print a string which is the result of concatenating each integer (as strings) togethere with commas.

This can be done really easily with the str.join method which takes an iterable of strings and then joins them together with a deliminator - which will be a comma (',') here.

So, the f.write line should be something like:

f.write('{}\n'.format(''.join(str(i) for i in line)))

or if the elements of line are already strings (it is impossible to tell from your current code), then you can use the more simple:

f.write('{}\n'.format(''.join(line)))

Upvotes: 1

Rakesh
Rakesh

Reputation: 82765

Replace

f.write('{}\n'.format(line))

With

f.write('{}\n'.format(",".join(line)))

Upvotes: 1

Related Questions