如何打印用户从输入中提供文件名的文件正文



我想知道,从用户提供的文件名中,我们是否可以获得文件的正文

这里是我的代码的样本

fname = input('Enter filename...')
fileObject = open(fname, 'r')
print(fname)

是的,您需要从文件中读取数据,然后将其打印出来,或者一次完成所有操作:

fname = input("What's the file name? ")
# this assumes it's on the same directory
with open(fname, 'r') as file:
print(file.read())

你可以试试这个:(也可以阅读Python官方文档(

with open(filename) as f:
content = f.read()
# you may also want to remove whitespace characters like `n` at the end of each line

print(content)