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.
所以基本上我想要删除空格和[]。
2 个解决方案
#1
1
Replace
取代
f.write('{}\n'.format(line))
With
与
f.write('{}\n'.format(",".join(line)))
#2
1
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.
目前,line是一个ints列表,我们需要打印一个字符串,它是将每个整数(作为字符串)与逗号连接在一起的结果。
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.
使用string .join方法可以很容易地做到这一点,该方法获取可迭代的字符串,然后将它们与一个分隔符连接在一起——这里是一个逗号(',')。
So, the f.write
line should be something like:
所以,f。写行应该是这样的:
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)))
#1
1
Replace
取代
f.write('{}\n'.format(line))
With
与
f.write('{}\n'.format(",".join(line)))
#2
1
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.
目前,line是一个ints列表,我们需要打印一个字符串,它是将每个整数(作为字符串)与逗号连接在一起的结果。
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.
使用string .join方法可以很容易地做到这一点,该方法获取可迭代的字符串,然后将它们与一个分隔符连接在一起——这里是一个逗号(',')。
So, the f.write
line should be something like:
所以,f。写行应该是这样的:
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)))