Python đọc file (Python 3)

moi nguoi oi cho minh hoi tai sao minh khong in luon file target ra duoc thang PowerShell no cu bao cai loi nay : ,<_io.TextIOWrapper name='.\\file de xoa.txt' mode='w' encoding='cp1252'>

doan code cua minh day ;

#muc dich la hoi co muon xoa noi dung trong “file de xoa.txt” hay khong ?

from sys import argv

script, filename = argv

print ("Ban co muon xoa file %s hay khong?" % filename)
print ("Neu muon huy xoa thi an nut ctrl c")
print ("neu muon tiep tuc thi an enter")

input ("Tiep tuc xoa du lieu")

print ("Dang mo file %s......vui long cho trong giay lat" % filename)

target = open (filename, "w")



print ("file cua ban da duoc xoa")
print ("ban muon viet gi vao file moi?")

line1 = input ("cau thu nhat")
line2 = input ("cau thu hai")
line3 = input ("cau thu ba")


target.write(line1 + "\n" + line2 + "\n" + line3)


target.close()


print("file moi cua ban co noi dung la:")

print (target.read())

cam on moi nguoi

Vì bạn open mà chưa .read().

4 Likes

vay thi minh phai sua lai nhu nao ha ban.

target = open (filename, "w").read()

minh viet lai nhu nay no van bao loi :

File "1.py", line 15, in <module>
    target = open (filename, "w").read()
io.UnsupportedOperation: not readable

Bạn để ý flag w, nó dùng để write chứ không phải dùng để read. Sửa lại có thể dùng:

target = open(filename, 'r').read

P/S: Có thể bạn không cần đến, nhưng open file trong Python thường đi kèm với contextmanager, bạn có thể dùng:

with open(filename, 'r') as content:
    print(content)
2 Likes

thanks ban nhe :slight_smile:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?