- 论坛徽章:
- 4
|
- import os
- def read_content(filename):
- '''assume file size is not big to affect operation, return all content in list.'''
- result = []
- if not os.path.exists(filename):
- return result
- try:
- file_handle = open(filename)
- result = file_handle.readlines()
- except IOError:
- pass
- finally:
- file_handle.close()
- return result
- def switch_content(source, target, pos1, pos2):
- '''use 2 tuple (row, col): pos1, pos2; to mark related switching position in source & target.'''
- line_s = source[pos1[0] - 1]
- line_t = target[pos2[0] - 1]
- s_list = line_s.split(' ')
- t_list = line_t.split(' ') # ''之间是有一个空格的
- t_list[pos2[1]-1] = s_list[pos1[1]-1]
- line_t = ' '.join(t_list) # ''之间是有一个空格的
- target[pos2[0]-1] = line_t
- return target
- def dump_result(filename, content):
- '''Dump content--list, into specified file.'''
- try:
- file_handle = open(filename, "w")
- file_handle.writelines(content)
- file_handle.close()
- return True
- except IOError:
- return False
- def main():
- source1 = read_content('a.txt')
- source2 = read_content('b.txt')
- content = switch_content(source1, source2, (2, 1), (3, 2))
- dump_result('b.txt', content)
- if __name__ == '__main__':
- main()
复制代码 |
|