使用文件对象打开和关闭文件:
fp=open("ram.txt","w")
fp.close()
Run Code Online (Sandbox Code Playgroud)
如果我们想在不使用文件对象的情况下打开和关闭文件,即;
open("ram.txt","w")
Run Code Online (Sandbox Code Playgroud)
我们需要写作close("poem.txt")还是写作close()好吗?
他们都没有给出任何错误......
只编写close(),它如何理解我们引用的文件?
我试图在整数的16位二进制表示上使用左移运算符
编写的代码如下:
def showbits(x):
return bin(x)[2:].zfill(16)
i=5225
print "Decimal %d is same as binary" % (i)
print showbits(i)
for j in range(0,5,1):
k=i<<j
print "%d right shift % gives" % (i,j)
print showbits(k)
Run Code Online (Sandbox Code Playgroud)
输出:
Decimal 5225 is same as binary
0001010001101001
5225 right shift 0ives
0001010001101001
5225 right shift 1ives
0010100011010010
5225 right shift 2ives
0101000110100100
5225 right shift 3ives
1010001101001000
5225 right shift 4ives
10100011010010000
Run Code Online (Sandbox Code Playgroud)
主要的问题是,当它移动前导'1'时,它并没有消失,而是在增加一点......
任何解决方案?
我们考虑以下代码:
fp=open('PR1.txt','r')
ch=fp.readlines()
print "%s" % (' '.join(ch))
print "\n"
fp.close()
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了错误:
IOError: [Errno 2] No such file or directory: 'PR1.txt'
Run Code Online (Sandbox Code Playgroud)
但是,当我提供其完整的位置,即;
fp=open('D:/PR1.txt','r')
Run Code Online (Sandbox Code Playgroud)
然后它正常工作......
是否有必要提供文件的完整位置或者还有其他一些方法?