我如何使用 python 读取和打印整个 .txt 文件?

How do i read and print a whole .txt file using python?

我对 python 完全陌生,我应该编写一个程序来读取整个 .txt 文件并打印它。该文件是一篇用我的母语(挪威语)写的文章,而且很长。我有三个版本应该做同样的事情,但都出错了。我已经在安装了 PyDev 的 bot PyCharm 和 eclipse 中进行了尝试,但我在两者上都遇到了相同的错误...

from sys import argv

import pip._vendor.distlib.compat

script, dev = argv

txt = open(dev)

print("Here's your file %r:" % dev)
print(txt.read())


print("Type the filename again:")h
file_again = pip._vendor.distlib.compat.raw_input("> ")

txt_again = open(file_again)

print(txt_again.read())

但这会出现错误:

Traceback (most recent call last):
File "/Users/vebjornbergaplass/Documents/Python eclipse/oblig1/src/1A/1A.py", line 5, in <module>
script, dev = argv
ValueError: not enough values to unpack (expected 2, got 1)

同样,我是 python 的新手,我四处搜索,但没有找到解决方案。

我的下一次尝试是:

# -*- coding: utf-8 -*-

import sys, traceback

fr = open('dev.txt', 'r')
text = fr.read()
print(text)

但这会出现以下错误:

Traceback (most recent call last):
    File "/Users/vebjornbergaplass/Documents/Python eclipse/oblig1/src/1A/v2.py", line 6, in <module>
        text = fr.read()

  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 26: ordinal not in range(128)

我不明白为什么我不工作。

我的第三次尝试是这样的:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
parser = argparse.ArgumentParser()

parser.add_argument("dev.txt", help="dev.txt")
args = parser.parse_args()
if args.filename:
    with open('dev.txt') as f:
        for line in f:
            name, _ = line.strip().split('\t')
            print(name)

这得到了错误:

usage: v3.py [-h] dev.txt
v3.py: error: the following arguments are required: dev.txt

欢迎就这些方法为何不起作用提供任何帮助。 提前谢谢你:D

file = open("File.txt", "r")
a = str(file.read())

print(a)

这是您要找的吗?

例如:

open ("fileA.txt", "r") as fileA:
    for line in fileA:
        print(line);

这是一个可能的解决方案:

f = open("textfile.txt", "r")
lines = f.readlines()
for line in lines:
    print(line)
f.close()

保存为例如myscript.py并执行:

python /path/to/myscript.py

因为第二种方法最简单,我会坚持下去。

您声明 dev.txt 的内容是挪威语,这意味着它将包含 non-ascii 个字符,例如 Æ,Ø,Å 等。python 解释器试图告诉你这个:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 26: ordinal not in range(128) 它不能将字节 0xC3 = 195 (decimal) 解释为 ascii 字符,它被限制在 128 个不同字符的范围内。

我假设您使用 UTF-8 作为编码,但如果不是,请更改第 2 行中的参数。

# -*- coding: utf-8 -*-

fr = open('dev.txt', 'r', encoding='utf-8')
text = fr.read()
print(text)

如果您不知道自己的编码,可以通过您的编辑器或use python to guess it找到它。

如果您的终端未配置为打印 Unicode 字符或正确映射它们,它也可能导致错误。您可能想看看 this question and its answers.


操作文件后,建议关闭。您可以通过 fr.close() 手动执行此操作,也可以让 python 自动执行此操作:

with open('dev.txt', 'r', encoding='utf-8') as fr:
    # automatically closes fr when leaving this code-block