关于Windows系统下,Python读取文件的问题。

在windows系统下,Python读取文件需要输入整个路径的名称,可以不是C盘,也可以是中文名字的路径。

 

输入的方法是函数 open(文件地址,’r’)

 

‘r’ 表示读取,’w’ 表示写入,’a’ 表示添加,’+’ 表示读写,’b’ 表示二进制访问

测试代码如下:

a)

filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

fobj.close()

 

运行后

>>>

Enter file name:G:\interesting\text.txt

I am a learner,

 

I like Python,

 

I want Python read this file.

 

Hello World

 

b) filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

print 'You makeit! Congratulations!'

 

fobj.close()

 

运行后

Enter file name:G:\interesting\text.txt

I am a learner,

You make it! Congratulations!

 

You make it! Congratulations!

I like Python,

You make it! Congratulations!

 

You make it! Congratulations!

I want Python read this file.

You make it! Congratulations!

 

You make it! Congratulations!

Hello World You make it! Congratulations!

之所以这里会有两行’ You make it! Congratulations!’是因为我在编辑text.txt时候,每一行后面都输入了两个回车

 

c)

filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

print '\n\

\

You make it! Congratulations!'

 

fobj.close()

运行后

>>>

Enter file name:G:\interesting\text.txt

I am a learner,

 

I like Python,

 

I want Python read this file.

 

Hello World

You make it! Congratulations!

在这里,我们发现,在print函数当中,’\n’会打印一个回车,’\’表示换行后继续打印,但是不管换几行,都会直接跳过这些回车,而不是打印这些回车。

 

d)更改文件名为’测试.txt’

filename = raw_input('Enter file name:')

fobj = open (filename, 'r')

for eachLine in fobj:

   print eachLine,

print '\n\

\

You make it! Congratulations!'

 

fobj.close()

 

运行后

>>>

Enter file name:G:\interesting\测试.txt

I am a learner,

 

I like Python,

 

I want Python read this file.

 

Hello World

You make it! Congratulations!

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值