终端读出txt文件时出现乱码
各位大神们,我写的这个代码为什么读一个txt读出来却是一堆乱码呢from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename}")
print(txt.read())
print('Type the filename again:')
file_again = input('>')
txt_again = open(file_again)
print(txt_again.read())
/Users/lizehong/Desktop/屏幕快照\ 2020-05-19\ 上午11.06.10.png
lizehongdeMacBook-Air:15_读取文件 lizehong$ python3.8 15_读取文件.py 15_text.txtHere's your file 15_text.txt
{\rtf1\ansi\ansicpg936\cocoartf1671\cocoasubrtf600
{\fonttbl\f0\fnil\fcharset0 Menlo-Regular;}
{\colortbl;\red255\green255\blue255;\red0\green0\blue0;}
{\*\expandedcolortbl;;\csgray\c0;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\pardirnatural\partightenfactor0
\f0\fs22 \cf2 \CocoaLigature0 Ashhhahakhakfhliaufehi\
fhaoiefhiofhvkdjbv\
adaiofhoiefojireofhovih}
Type the filename again:
>15_text.txt
{\rtf1\ansi\ansicpg936\cocoartf1671\cocoasubrtf600
{\fonttbl\f0\fnil\fcharset0 Menlo-Regular;}
{\colortbl;\red255\green255\blue255;\red0\green0\blue0;}
{\*\expandedcolortbl;;\csgray\c0;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx560\tx1120\tx1680\tx2240\tx2800\tx3360\tx3920\tx4480\tx5040\tx5600\tx6160\tx6720\pardirnatural\partightenfactor0
\f0\fs22 \cf2 \CocoaLigature0 Ashhhahakhakfhliaufehi\
fhaoiefhiofhvkdjbv\
adaiofhoiefojireofhovih} 试着这样打开?
txt = open(filename,encoding='utf-8') open那里加个参数:
encoding="utf-8" 或者encoding="gbk" lizehongdeMacBook-Air:15_读取文件 lizehong$ python3.8 15_读取文件.py 15_text.txtHere's your file 15_text.txt
> 15_text.txt
> 15_text.txt
> 15_text.txt
> 15_text.txt
> 15_text.txt
> 15_text.txt
> 15_text.txt
> 15_text.txt
> 15_text.txt
各位,不行啊
LittleLito666 发表于 2020-5-19 11:15
各位,不行啊
查看原始文件编码格式 你打开的文件并非文本文件,而是RTF文件,RTF是RichTextFormat的缩写,意即富文本格式,这是一种类似DOC格式(Word文档)的文件。windows中可以用word或者写字板打开,MAC OS用也有相应的程序可以打开。所以作为练习,你需要换一个真正的文本文件了。
页:
[1]