我對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 –