我在文本文件中放了一个列表。我希望python读取文本文件并将内容作为列表返回。但是,它是以字符串形式读取内容:
文字档案:
['a','b','c']
的Python:
ids=[]
writtenFile =open('file.txt')
readFile=writtenFile.read()
ids= readFile
writtenFile.close()
print ids
返回的内容是[' a'' b'' c']作为字符串,而不是列表或文本。有没有办法可以从文本文件中检索[' a'''' c']然后将其存储在ids字符串中以便ids是一个列表[' a'' b'' c']而不是字符串? " ['一个'' B'' C']"
答案 0 :(得分:2)
使用ast.literal_eval
逐字地评估文件的内容,因为它写的实际上是一个字符串:
data = ast.literal_eval(open('data.txt').read()) # create file, read contents, evaluate
答案 1 :(得分:1)
如果你只是采用相同的格式,那么剥离和拆分的最快方式就是:
org 100h
;mov ah,0ah
;mov dx,offset place
;int 21h ; getting the place(directory) of the file
;ADD 0 TO END OF STRING <==================================
;mov si,offset place
;inc si
;mov dl,[si] ;<== LENGTH OF STRING IS BYTE, NOT WORD
;mov dh,0 ;<================== CLEAR DH TO USE DX
;inc dx
;add si,dx ;<========= SI POINTS TO FINAL CHAR + 1
;mov [byte ptr si],0 ;<========= THE NUMBER ZERO HAS NO SIZE
;LINE BREAK.
;;mov ah,02
;mov dl,13
;int 21h
;mov ah,02
;mov dl,10
;int 21h
mov ah,0ah
mov dx,offset filename
int 21h ;getting the file name
;ADD 0 TO END OF STRING <==================================
mov si,offset filename
inc si
mov dl,[si] ;<== LENGTH OF STRING IS BYTE, NOT WORD
mov dh,0 ;<================== CLEAR DH TO USE DX
inc dx
add si,dx ;<========= SI POINTS TO FINAL CHAR + 1
mov [byte ptr si],0 ;<========= THE NUMBER ZERO HAS NO SIZE
;LINE BREAK.
mov ah,02
mov dl,13
int 21h
mov ah,02
mov dl,10
int 21h
;call gotoplace ;go to the place of the file
;------------------
call openfile ;open the file
;------------------
mov ah,3fh
mov si,offset filehandle
mov bx,[si] ;move file adress to bx
mov cx,40000 ;numbers of bytes to read
mov dx,offset buff ;pointer to read buffer
int 21h
mov si,offset filesize ;move si pointer to filesize
mov [si],ax ;move to filesize how many bytes read
;------------------
;writing on the screen ->
mov bx,offset buff ;move bx pointer of buffer
mov si,offset filesize
mov cx,[si] ;move cx how many to write
startwrite:
mov ah,2
mov dl,[bx] ;move dl letter in place [bx]
int 21h
inc bx
dec cx
jnz startwrite
;WAIT UNTIL USER PRESS ANY KEY <===========================
mov ah,7
int 21h
;FINISH PROGRAM <==========================================
mov ax, 4c00h
int 21h
proc gotoplace
mov ah,3bh
mov dx,offset place ;move offset place to dx
add dx,2
int 21h
ret
endp gotoplace
proc openfile
mov ah,3dH
mov al,2 ;open for read / write
mov dx,offset filename ;move dx offset filename
add dx,2
int 21h
;--------------------------
mov si,offset filehandle ;move offset filehandle(location in the memory) to si
mov [si],ax ;move the file adress to the 'filehandle'(location in the meory'
ret
endp openfile
ret
filehandle dd ?
filename db 40
db 42 dup (0)
place db 40
db 42 dup (0)
buff db 40000 dup (0)
filesize dw ? ;<========= IN 8086 WE CANNOT READ MORE THAN 64KB.