我对python来说是全新的,我应该编写一个能够读取整个.txt文件并打印出来的程序。该文件是我的第一语言(挪威语)的文章,并且很长。我有三个版本应该做同样的事情,但都会出错。我在BOT PyCharm尝试和安装PyDev的Eclipse和我得到两个同样的错误......如何使用python读取和打印整个.txt文件?
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)
再说,我是新来的蟒蛇,我四处搜寻,但没有找到解决办法。
我的下一个尝试是这样的:
# -*- 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
纠正过去的错误。 parser.add_argument()函数需要参数名称。参数值由您的脚本的用户给出。用1个参数调用脚本:python v3.py dev.txt –