如何修复Unicode编码错误并实现DataFrame转TXT的Python函数?
Fixing Your DataFrame to TXT Export Issues
Let's tackle both the formatting and encoding problems you're facing step by step:
1. Root Causes of Your Issues
- Encoding Error: On Windows, Python defaults to the system's "charmap" encoding when opening files, which can't handle Unicode characters like
ńin your Yoruba text. We need to explicitly use UTF-8 to support these characters. - Formatting & Overwriting: Your current code uses
'w'mode inside the row loop, which overwrites the entire file every time you write a single row. Also, the header usesrjust(40)while rows useljust(20)—this mismatched padding breaks column alignment completely.
2. Corrected Code
import pandas as pd def print_table(dataframe): headers = dataframe.columns.to_list() # Define a consistent column width (adjust this value based on your longest content) col_width = 45 # Open the file once with UTF-8 encoding to avoid overwrites and encoding failures with open('file.txt', 'w', encoding='utf-8') as file: # Write headers with uniform left-aligned padding file.write(''.join(header.ljust(col_width) for header in headers) + '\n') # Loop through each row and apply the same padding for alignment for row in dataframe.values.tolist(): formatted_row = ''.join(str(item).ljust(col_width) for item in row) file.write(formatted_row + '\n') df = pd.DataFrame({ 'Yoruba': [ 'Wèrè èèyàn ní ńwípé irú òun ò sí; irú ẹ̀ẹ́ pọ̀ ó ju ẹgbàágbèje lọ.', 'Wọ́n ńpe gbẹ́nàgbẹ́nà ẹyẹ àkókó ńyọjú.' ], 'Translation': [ 'Only an imbecile asserts that there is none like him or her; his or her likes are numerous, numbering more than millions.', 'The call goes out for a carpenter and the woodpecker presents itself.' ], 'Meaning': [ 'No one is incomparable.', "One should not think too much of one's capabilities." ] }) print_table(df)
3. Key Modifications Explained
- UTF-8 Encoding: Added
encoding='utf-8'to theopen()call—this ensures all Unicode characters in your Yoruba text are saved without errors. - Single File Opening: We open the file once outside the loop (using
'w'mode) instead of re-opening it for every row. This prevents overwriting and is more efficient. - Consistent Padding: Used a fixed
col_widthand appliedljust(col_width)to both headers and rows. This keeps each column aligned neatly, so headers line up with their corresponding content. - Newlines: Added
'\n'after writing headers and rows to ensure each entry starts on a new line, making the file readable.
4. Sample Output Preview
Your file.txt will now have clean, aligned content (truncated for brevity):
Yoruba Translation Meaning Wèrè èèyàn ní ńwípé irú òun ò sí; irú ẹ̀ẹ́ pọ̀ ó ju ẹgbàágbèje lọ. Only an imbecile asserts that there is none like him or her; his or her likes are numerous, numbering more than millions. No one is incomparable. Wọ́n ńpe gbẹ́nàgbẹ́nà ẹyẹ àkókó ńyọjú. The call goes out for a carpenter and the woodpecker presents itself. One should not think too much of one's capabilities.
内容的提问来源于stack exchange,提问作者segun
相关产品推荐
相关产品推荐

