简体   繁体   English

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

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

I am totally new to python, and I am supposed to write a program that can read a whole .txt file and print it. 我是python的新手,应该编写一个程序,该程序可以读取整个.txt文件并进行打印。 The file is an article in my first language(Norwegian), and long. 该文件是用我的母语(挪威语)撰写的一篇文章,内容冗长。 I have three versions that should do the same thing, but all get error. 我有三个版本应该做同样的事情,但是都出现错误。 I have tried in bot PyCharm and eclipse with PyDev installed, and i get the same errors on both... 我已经在安装了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())

But this gets the errors: 但这会得到错误:

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)

Again, i am new to python, and i searched around, but didn't find a solution. 再次,我是python的新手,我四处搜寻,但是没有找到解决方案。

My next attempt was this: 我的下一个尝试是:

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

import sys, traceback

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

But this gets these errors: 但这会得到以下错误:

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)

I do not understand why i doesn't work. 我不明白为什么我不工作。

My third attempt looks like this: 我的第三次尝试如下所示:

#!/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)

And this gets the errors: 这会得到错误:

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

Any help to why these doesnt work is welcome. 欢迎对这些无效的任何帮助。 Thank you in advance :D 预先谢谢你:D

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

print(a)

Is this what you were looking for? 这是您要找的东西吗?

For the 2nd approach is the simplest, I'll stick to it. 因为第二种方法最简单,所以我会坚持下去。

You stated the contents of dev.txt to be Norwegian, that means, it will include non-ascii characters like Æ,Ø,Å etc. The python interpreter is trying to tell you this: 您将dev.txt的内容dev.txt成是挪威语,这意味着它将包含非ASCII字符,例如Æ,Ø,Å等。python解释器试图告诉您这一点:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 26: ordinal not in range(128) It cannot interpret the byte 0xC3 = 195 (decimal) as an ascii character, which is limited to a range of 128 different characters. UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 26: ordinal not in range(128)它无法将字节0xC3 = 195 (decimal)为ascii字符,该字符限制为128个不同字符的范围。

I'll assume you're using UTF-8 as encoding but if not, change the parameter in line 2. 我假设您使用的是UTF-8编码,但如果没有,请更改第2行中的参数。

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

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

If you do not know your encoding, you can find it out via your editor or use python to guess it . 如果您不知道编码,则可以通过编辑器找到它,或者使用python猜测它

Your terminal could also cause the error when it's not configured to print Unicode Characters or map them correctly. 当您的终端未配置为打印Unicode字符或正确映射它们时,它也可能导致错误 You might want to take a look at this question and its answers. 您可能想看看这个问题及其答案。


After operating a file, it is recommended to close it. 操作文件后,建议将其关闭。 You can either do that manually via fr.close() or make python do it automatically: 您可以通过fr.close()手动执行此操作,也可以让python自动执行此操作:

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

For example: 例如:

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

This is a possible solution: 这是一个可能的解决方案:

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

Save it as for example myscript.py and execute it: 将其另存为例如myscript.py并执行:

python /path/to/myscript.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM