我正在尝试构建一个从单独的文本文件中读取值的程序。在这种情况下,它被命名为" Test.lang"。它包含文本" Hello World"。
我的程序工作得很好:
from sys import *
def open_file(filename):
print (filename)
def run():
data = open_file(argv[1])
run()
然后,当我尝试将其更改为:
from sys import *
def open_file(filename):
data = open(filename, "r").read()
print (data)
def run():
data = open_file(argv[1])
run()
它不起作用。我得到4个错误:
Traceback (most recent call last):
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 10, in <module>
run()
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 8, in run
data = open_file(argv[1])
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 4, in open_file
data = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'test.lang'
让我感到困惑的是最后一个。以前的程序是如何工作的,但现在test.lang不存在? 请帮帮我。
答案 0 :(得分:0)
这是你如何做到的。
阅读文件:
file = open('Directory Of The File.txt', 'r')
MyVariable = file.read()
file.close()
写一个文件:
file = open('Directory Of The File.txt', 'w')
file.write('Insert Text, Variable or Other Data Here!')
file.close()
就这么简单! 您可以为.lang或任何其他支持的文件扩展名更改.txt! 请回复并告诉我这是否适合您:)